0

我收到下面的代码错误.. 我把头撞在墙上,因为我不知道为什么我似乎无法用每次按下按钮的次数(计数器)更新消息按下按钮...

- (IBAction)countButtonTapped:(id)sender {

    self.pressCount+=1;
    //int count = (int)self.pressCount;

    //[self.tapCountButton setTitle:@"I've been tapped %i time(s)!" forState:UIControlStateNormal];
    //[self.tapCountButton setTitle:@"I've hit the main button!" forState:UIControlStateNormal];
    //NSLog(@"I've been tapped %lu time(s)!", (unsigned long)self.pressCount);
    [(UIButton *)sender setTitle:@"I've been tapped %@ time(s)!",self.pressCount forState:UIControlStateNormal];
4

2 回答 2

2

听起来您只需要一个字符串格式化程序。

尝试这个:

- (IBAction)countButtonTapped:(id)sender {
    UIButton * button = (UIButton *) sender; 
    self.pressCount+=1;
    NSString * titleForButton = [NSString stringWithFormat: @"I've been tapped %d time(s)!",self.pressCount]
    [button setTitle: titleForButton forState: UIControlStateNormal];
}

这里的另一个区别是“self.pressCount”可能是一个 NSInteger,所以你想使用“ %d”作为格式参数,而不是“ %@”,这意味着 NSString 对象。

于 2013-09-16T02:15:34.707 回答
0

确保在您的故事板中,您的 UIButton 仅在触地得分时调用 IBAction。也许您正在其他 UIButton 状态上调用您的 IBAction。

我会这样做

    @implementation v1ViewController

    ...
    static int counter = 0;


    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

    //initialize
    counter = 0
    }

    - (IBAction)countButtonTapped:(id)sender {

        counter++;

    NSLog("counter: %d ...", counter);

UIButton *button = (UIButton *) sender;
        [button setTitle:@"I've been tapped %d time(s)!",counter forState:UIControlStateNormal];

    }
于 2013-09-16T02:40:28.280 回答