如何在iOS中的UITableView Cell中为UIButton设置标记值?

时间:2015-11-19 10:40:19

标签: ios objective-c uitableview uibutton

我使用了自定义单元格并在UIButton中创建了UITableViewCell。我想更改按钮状态,如下面的屏幕截图。 Xcode的新手可以任何人指导我。提前致谢

enter image description here

这是我的代码

PrivacyCell.h

@property (strong, nonatomic) IBOutlet UIButton *on_offBtn;

- (IBAction)on_offBtnAction:(UIButton *)sender;

@property (nonatomic,assign) BOOL on_image;

@property (nonatomic,assign) BOOL off_image;

PrivacyCell.m

#import "PrivacyCell.h"

- (IBAction)on_offBtnAction:(UIButton *)sender {
     if (on_image == YES) {
         [_on_offBtn setImage:[UIImage imageNamed:@"on_icon.png"]                      forState:UIControlStateNormal];
         on_image = NO;
     } else if (on_image == NO)  {
         [_on_offBtn setImage:[UIImage imageNamed:@"off_icon.png"] forState:UIControlStateNormal];
         on_image = YES;
     }
}

4 个答案:

答案 0 :(得分:0)

cellforRowAtIndexPath设置按钮属性中

btn.tag = indexPath.row;
[btn setImage:[UIImage imageNamed:@"off_btn.png"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"on_btn.png"] forState:UIControlStateSelected];

并在点击事件中更改其状态

- (IBAction)on_offBtnAction:(UIButton *)sender
{
     sender.selected = !sender.selected;
     // [yourTableVew reloadData];
}

答案 1 :(得分:0)

您可以在此处设置标记

PrivacyCell.m

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self)
    {
       on_offBtn.tag = 100;
    }
    return self;
 }

然后你可以使用

UIButton *button = (UIButton *)[cell viewWithTag:100];
button.selected = true;

但你也可以使用你的财产。

答案 2 :(得分:0)

即使您可以在UIButton

中将标记设置为cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   static NSString *cellIdentifier = @"Cell";

   PrivacyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

   if (cell == nil) {
      cell = [[PrivacyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
      // or you can use custom method for init
   }

   ...

   cell.on_offBtn.tag = indexPath.row;

   ...

   return cell;

}

答案 3 :(得分:0)

您可以从故事板为UITableViewCell中的按钮创建IBAction,然后只要您点击该按钮,就会调用此方法。您将获得所单击按钮的索引,并可以相应地执行任何任务。

如果tabelViewCell上有多个按钮,这会有所帮助。

- (IBAction)tidesButtonAction:(id)sender
{
     CGPoint buttonPosition = [sender convertPoint:CGPointZero
                                       toView:self.tableView];
     NSIndexPath *tappedIP = [self.tableView indexPathForRowAtPoint:buttonPosition];
     NSString *text = [tidesURLArray objectAtIndex:tappedIP.row];
}