Creating a UIButton with Image

Discussion in 'iOS Programming' started by Lakario, Nov 3, 2008.

  1. Lakario macrumors member

    Oct 29, 2008
    I am trying to implement a button in a subClass of UITableCell and I'm having trouble getting it to show up.

    I suppose first I should start by asking if that is even possible? My TableCell implements the cell click delegate, but I also need a button on the cell itself that is clickable without firing the row click.

    Here is how my button is being implemented:

    - (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
        if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
    		UIView *myContentView = self.contentView;
    		[self.defaultButton setImage:uncheckedImage forState:UIControlStateNormal];
    		[self.defaultButton setTitle:@"Default" forState:UIControlStateNormal];
    		[myContentView addSubview:self.defaultButton];
    		[self.defaultButton release];
         //other code....
         [myContentView bringSubviewToFront:self.defaultButton];
        return self;
    - (void)layoutSubviews {
    #define LEFT_COLUMN_OFFSET 5
    #define	LEFT_COLUMN_WIDTH 50
    #define RIGHT_COLUMN_OFFSET 30
    #define RIGHT_COLUMN_WIDTH 240
    #define UPPER_ROW_TOP 8
    	[super layoutSubviews];
    	CGRect contentRect = self.contentView.bounds;
    	if(!self.editing) {
    		CGFloat boundsX = contentRect.origin.x;
    		CGRect frame;
                    // other code...
    		// Place default button
    		UIButton *checkBoxButton = self.defaultButton;
    		frame = [checkBoxButton frame];
    		frame.origin.x = boundsX + LEFT_COLUMN_OFFSET;
    		frame.origin.y = 12;
    		checkBoxButton.frame = frame;
    As it is now, the button does not appear on the cell at all. The button itself should only be an image without a title, and I made sure the image was working correctly by loading it an ImageView. I am just unsure if there is a problem with how I declaring the button.
  2. SqueegyX macrumors regular

    Mar 24, 2008
    It looks like you never actually create the button. In your cell's init method do something like

    self.defaultButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 32, 32)];
    Unles syou are creating it somewhere else? Or the cell loaded from a nib?
  3. Lakario thread starter macrumors member

    Oct 29, 2008
    I think you're right about that let me go fix that haha... As for your other comment, I was actually wondering if and/or how I could define the Cell with a Nib file. Is that possible?
  4. SqueegyX macrumors regular

    Mar 24, 2008
    I think I have heard that it is, but its not something I have done.
  5. Lakario thread starter macrumors member

    Oct 29, 2008
    Can anyone confirm?

Share This Page