【发布时间】:2015-07-09 08:59:46
【问题描述】:
我有一个自定义 UITableViewCell,其中包含 3 个 UIButtons,我希望当我点击一个按钮时,我的单元格的背景会发生变化。但是当我点击一个按钮时,UITableView 中的所有单元格都会改变它们的背景,而不仅仅是里面有按钮的单元格。
自定义单元格 (.h)
@interface SCActionsViewCell : UITableViewCell
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, strong) UIButton *thanksButton;
@property (nonatomic, strong) UIButton *commentsButton;
@property (nonatomic, strong) UIButton *reButton;
@end
自定义单元格 (.m)
#define TEXT_BUTTON_SIZE 25
@implementation SCActionsViewCell
- (void)awakeFromNib {
// Initialization code
self.backgroundColor = [UIColor colorLight];
_thanksButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width/3, actionsCellHeight)];
_commentsButton = [[UIButton alloc] initWithFrame:CGRectMake(self.contentView.frame.size.width/3, 0, self.contentView.frame.size.width/3, actionsCellHeight)];
_reButton = [[UIButton alloc] initWithFrame:CGRectMake(self.contentView.frame.size.width*2/3, 0, self.contentView.frame.size.width/3, actionsCellHeight)];
_thanksButton.titleLabel.font = [UIFont fontWithName:kFontAwesomeFamilyName size:TEXT_BUTTON_SIZE];
_commentsButton.titleLabel.font = [UIFont fontWithName:kFontAwesomeFamilyName size:TEXT_BUTTON_SIZE];
_reButton.titleLabel.font = [UIFont fontWithName:kFontAwesomeFamilyName size:TEXT_BUTTON_SIZE];
[_thanksButton setTitle:[NSString fontAwesomeIconStringForEnum:FAThumbsOUp] forState:UIControlStateNormal];
[_commentsButton setTitle:[NSString fontAwesomeIconStringForEnum:FACommentsO] forState:UIControlStateNormal];
[_reButton setTitle:[NSString fontAwesomeIconStringForEnum:FARetweet] forState:UIControlStateNormal];
[_thanksButton setTitleColor:[UIColor sGreen] forState:UIControlStateSelected];
[_reButton setTitleColor:[UIColor sGreen] forState:UIControlStateSelected];
[self addSubview:_thanksButton];
[self addSubview:_commentsButton];
[self addSubview:_reButton];
}
@end
SCViewDataSource(表视图数据源)
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.posts.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SCActionsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SCActionsViewCell" forIndexPath:indexPath];
cell.tableView = tableView;
cell.indexPath = indexPath;
[cell.thanksButton addTarget:(SCViewController *)tableView.delegate action:@selector(touched:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
SCViewController.m
-(void)touched:(UIButton *)button{
NSLog(@"indexPath : %@",((SCActionsViewCell *)button.superview).indexPath);
((SCActionsViewCell *)button.superview).backgroundColor = [UIColor blueColor];
}
在这种情况下,当我点击单元格中的ThanksButton 时,所有单元格的背景都会更改为蓝色...
【问题讨论】:
标签: ios objective-c iphone uitableview uibutton