如何使用相同按钮的动作和插座

时间:2016-06-10 07:20:56

标签: ios objective-c ibaction iboutlet

我有一个像按钮,它有一个图像,我必须在点击它之后在该按钮中放置一些动作,诸如获得喜欢计数和显示在该按钮上的动作(喜欢计数)。这样做我得到一个错误,出口无法连接到重复的内容。请告诉我一些我将如何做到这一点。

// here is my code how i am doing it but its giving me storyboard error

- (IBAction)likeButtonAction:(id)sender {

    if(_likeButtonOutlet.selected) {

        NSManagedObject *record = [self.fetchedResultsController valueForKey:@"total_likes"];   

        //here on the above line i am fetching the count of likes and below i am sitting it to the button outlet

        [_likeButtonOutlet setValue:record forKey:@"total_likes"];

    }

}

3 个答案:

答案 0 :(得分:0)

您无需保留对UIButton的引用,只需访问sender即可。

- (IBAction)likeButtonAction:(UIButton *)sender {

    NSInteger totalLikes = [[NSUserDefaults standardUserDefaults]integerForKey:@"total_likes"];

    if (sender.selected) {
        sender.selected = NO;
        totalLikes--;
    } else {
        sender.selected = YES;
        totalLikes++;
    }

    [sender setTitle:[NSString stringWithFormat:@"Likes %ld", (long)totalLikes] forState:UIControlStateNormal];
    [[NSUserDefaults standardUserDefaults]setInteger:totalLikes forKey:@"total_likes"];
}

答案 1 :(得分:0)

正如您所说,自定义单元格中有_dislikeButtonOutlet。您错误地将其连接到view controller

  

您需要将插座连接到自定义单元而不是视图   控制器

答案 2 :(得分:0)

首先,您需要将按钮插座连接到自定义单元类。单击助理编辑器

enter image description here  然后像这样打开自定义单元格

enter image description here  然后将按钮插座连接到customCell类。 然后在tableview委托方法cellForRowAtIndexPath ..添加以下代码

 cell.likeBtn.addTarget(self, action: #selector(likeBtnClicked), forControlEvents: .TouchUpInside)

然后在视图控制器中定义func likeBtnClicked。然后将likeButtonAction的代码放在likeBtnClicked中。希望它有所帮助。