如何在UITableViewCell中单击UIbuttion时更改uilabel文本

时间:2014-10-22 08:48:20

标签: ios cocoa-touch uitableview uikit

我有UITableViewCell单元格显示在此自定义单元格下方有两个按钮用于添加/减去产品数量。我已将当前数量设置为+按钮标记并且能够获取。但我将如何设置标签文本2等等当用户点击+按钮时。

I have UITableViewCell

  

我不想更改表视图的DataSource,即在数组中添加增量值,数据从UITableView进入,然后重新加载tableView。

在探索SO i Find

    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tblCart];
NSIndexPath *hitIndex = [self.tblCart indexPathForRowAtPoint:hitPoint]; 

获取具有按钮的单元格的NSIndexPath。

3 个答案:

答案 0 :(得分:1)

您应该在delegate文件

上创建CustomCell.h方法
@class CustomCell;

@protocol CellDelegate <NSObject>

-(void)plusButtonClick:(CustomCell *)cell;

@end

.h文件的内部接口

@interface CustomCell : UITableViewCell
@property id<CellDelegate> delegate;
@end

然后在你的plusButton的Click事件中调用来自delegate的{​​{1}}

CustonmCell.m

现在在if ([delegate respondsToSelector:@selector(plusButtonClick:)]) { [delegate plusButtonClick:self]; }

viewController

希望这就是你想要的。

答案 1 :(得分:1)

如果您的单元格是自定义的,并且具有自己的自定义类,您可能宁愿在那里进行,而不是在TableViewController(例如MyCell)。 你班上有按钮,所以我假设你有一个自定义类,每个按钮都有-(IBAction)个?或者你做了别的什么?如果您不这样做,那么我推荐它。然后你可以用这样的东西(在MyCell.m中)解决它:

#import "MyCell.h"

@implementation MyCell

/*...*/

-(IBAction)addQuantity{
    self.quantity++;
    [self.txtQuantity setText:[NSString stringWithFormat:@"%i", self.quantity]];
    //Do something more here
}
-(IBAction)subQuantity{
    self.quantity--;
    if(self.quantity<0){self.quantity = 0;}
    [self.txtQuantity setText:[NSString stringWithFormat:@"%i", self.quantity]];
    //Do something more here
}

/*...*/

@end

在此示例中,您在@property int quantity; - 文件中声明了属性MyCell.h,以及名为{{1}的文本字段的IBOutlet }。此代码仅更新标签的文本和单元格自己的数量属性,但不更新数据源。但是,您也应该更新数据源(尽管您不必重新加载tableView)。所以在我写的地方&#34; //在这里做更多的事情&#34;,您应该从自定义单元格创建一个委托方法到tableView或tableViewController,让它知道数量字段已更改。

答案 2 :(得分:0)

我使用以下

实现了所需的功能
-(void)addQ:(UIButton*)sender

{
    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tblCart];
    NSIndexPath *hitIndex = [self.tblCart indexPathForRowAtPoint:hitPoint];
    NSInteger num=sender.tag;
    num=num+1;
    NSLog(@"%ld",(long)sender.tag);
    NSLog(@"hitIndex.row  is %ld",(long)hitIndex.row);
    [self alterTheQuantity:hitIndex.row  Num:num];
}
-(void)minusQ:(UIButton*)sender
{
    NSInteger num=sender.tag;
    num=num-1;
    if(num <0){
        num=0;
    }
    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tblCart];
    NSIndexPath *hitIndex = [self.tblCart indexPathForRowAtPoint:hitPoint];

    [self alterTheQuantity:hitIndex.row  Num:num];
}