dal*_*ijn 5 objective-c uibutton uitableview ios
我有TableView自定义类型的细胞.原型cell我有3个按钮.我希望能够在按下另一个时更改按钮标题.我试着这个:
- (IBAction) doSomething:(id) sender {
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.myTableView];
NSIndexPath *hitIndex = [self.myTableView indexPathForRowAtPoint:hitPoint];
NSLog(@"%ld", (long)hitIndex.row); //This works and I can see the row which button placed
MyCustomViewCell *cell = [_myTableView dequeueReusableCellWithidentifier:@"myCell"];
//I'm tried this:
cell.button.titleLabel.text = @"111";
//and I'm tried this:
[cell.button setTitle:@"222" forState:UIControlStateNormal];
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath(NSIndexPath *)indexPath {
MyCustomViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
if (!cell) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
cell.accessoryType= UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = _productNameForClearance;
cell.imageView.image = _productImageForBasket;
return cell;
}
Run Code Online (Sandbox Code Playgroud)
您的代码不起作用的原因是此代码为您提供了一个完全不相关的单元格:
MyCustomViewCell *cell = [_myTableView dequeueReusableCellWithidentifier:@"myCell"];
Run Code Online (Sandbox Code Playgroud)
它具有正确的类,因此您可以修改它而不会出现错误,但它不是UITableView.
不过,您应该有一些非 UI 状态来告诉您要显示什么标题:否则,将带有新标题的单元格从屏幕上滚动并重新打开将返回旧标题,这是错误的。
为了正确完成您想要实现的目标,您需要在两个地方实现更改:首先,代码doSomething应该修改负责更改标题的模型状态,如下所示:
// This needs to be part of your model
NSMutableSet *rowsWithChangedTitle = ...
- (IBAction) doSomething:(id) sender {
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.myTableView];
NSIndexPath *hitIndex = [self.myTableView indexPathForRowAtPoint:hitPoint];
NSLog(@"%ld", (long)hitIndex.row); //This works and I can see the row which button placed
[myModel.rowsWithChangedTitle addObject:@(hitIndex.row) ];
[self.myTableView reloadData];
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要tableView:cellForRowAtIndexPath:像这样更改您的方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomViewCell *cell = [_myTableView dequeueReusableCellWithidentifier:@"myCell"];
...
if ([myModel.rowsWithChangedTitle containsObject:@(indexPath.row)]) {
cell.button.titleLabel.text = @"111";
[cell.button setTitle:@"222" forState:UIControlStateNormal];
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2472 次 |
| 最近记录: |