gpt4 book ai didi

ios - CustomCell 标签值不变

转载 作者:行者123 更新时间:2023-11-28 18:36:24 26 4
gpt4 key购买 nike

我用 UIButtonUILabel 创建了一个 customCell

代码在这里:

ItemViewController.h:

@interface ItemViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
NSArray *arr;
IBOutlet ItemCustomCell *itemCell;
}

@property(nonatomic,retain)IBOutlet UITableView *tblItem;

ItemViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableItem";

ItemCustomCell *cell = (ItemCustomCell *) [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"ItemCustomCell" owner:self options:nil];
cell = itemCell;
}

cell.btnPlus.tag=indexPath.row;
[cell.btnPlus addTarget:self action:@selector(incrementValue:) forControlEvents:UIControlEventTouchUpInside];

return cell;
}

-(void)incrementValue:(UIButton *)btnAdd
{
NSLog(@"btn%d",btnAdd.tag);
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:btnAdd.tag inSection:0];
ItemCustomCell *cell = (ItemCustomCell*)[tblItem cellForRowAtIndexPath:indexPath];
cell.lblCount.text=[NSString stringWithFormat:@"%d",[cell.lblCount.text intValue]+1];

}

ItemCustomCell.h

@interface ItemCustomCell : UITableViewCell
{


}

@property(nonatomic,strong)IBOutlet UIButton *btnPlus;
@property(nonatomic,assign)IBOutlet UILabel *lblCount;

标签的默认值为 1。当我单击按钮时,它会显示下一个值。

当我向上或向下滚动时,tableView 标签值重置为 1。我在这里做错了什么?

最佳答案

对于customCell,需要在Xib中指定它的复用标识和类名,加载到你的cell中复用:

    cell = [[[NSBundle mainBundle] loadNibNamed:@"ItemCustomCell" owner:self options:nil] lastObject];

编辑

最好使用 IBOutlet 和委托(delegate)在 CustomCell 中实现操作,然后使用标签。

//ItemCustomCell.h
@class ItemCustomCell;
@protolcol ItemCustomCellDelegate
-(void) clickPlusButtonInsideCell:(ItemCustomCell *)cell;
@end
@interface ItemCustomCell
@property(weak, nonatomic) id<ItemCustomCellDelegate> delegate;
//Hookup with your view in Xib
@property (weak, nonatomic) IBOutlet UILabel *label;
-(IBACtion)clickPlusBut:(id)sender;
@end
//ItemCustomCell.m
-(IBACtion)clickPlusBut:(id)sender{
[self.delegate clickPlusButtonInsideCell:self];
}

使用

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableItem";

ItemCustomCell *cell = (ItemCustomCell *) [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"ItemCustomCell" owner:self options:nil] lastObject];
}
cell.delegate = self;

return cell;
}

-(void) clickPlusButtonInsideCell:(ItemCustomCell *)cell{
cell.label.text = @"something";
}

关于ios - CustomCell 标签值不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18228037/

26 4 0