How can I add a button as an accessory on a table view?
So, I have this code
UIButton *accessoryButton = [[UIButton alloc] init];
UIImage *accImage = [UIImage imageNamed:@"S开发者_运维百科hareAccButton.png"];
[accessoryButton setImage:accImage forState: UIControlStateNormal];
UIView *accView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 40, 15)];
[accView addSubview:accessoryButton];
cell.accessoryView = accView;
In this, I was trying to make a button an accessory for a table view cell. This doesn't work, and I am wondering how I can do this successfully. Also, how can I then connect those buttons to functions?
I guess you missed the frame of the button. Just init the button with a frame. As jamihash told, you can directly assign the button as accessoryView of a cell. I hope the following code should work.
UIButton *accessoryButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIImage *accImage = [UIImage imageNamed:@"ShareAccButton"];
[accessoryButton setImage:accImage forState: UIControlStateNormal];
[accessoryButton addTarget:self action:@selector(yourMethodName) forControlEvents:UIControlEventTouchUpInside];
[cell setAccessoryView:accessoryButton];
UIButton is a subclass of UIView so you could set cell.accessoryView to accessoryButton. To setup some action on button pressed use the (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents method.
精彩评论