PDA

View Full Version : Creating a UIButton with Image




Lakario
Nov 3, 2008, 12:46 PM
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.



SqueegyX
Nov 3, 2008, 01:35 PM
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?

Lakario
Nov 3, 2008, 01:54 PM
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?

SqueegyX
Nov 3, 2008, 02:10 PM
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?

I think I have heard that it is, but its not something I have done.

Lakario
Nov 4, 2008, 09:42 AM
I think I have heard that it is, but its not something I have done.

Can anyone confirm?