突出显示的UIButton状态的不同图像




对于UIButton的高亮显示状态,我需要2不同的图像。

我有以下几行代码:

- (IBAction)buttonPressed:(id)sender
{
    UIImage *followImageHighlighted = [UIImage imageNamed:@"follow-hilite.png"];
    UIImage *unfollowImageHighlighted = [UIImage imageNamed:@"unfollow-hilite.png"];
    if ([sender isSelected]) {
        // set this image for the next time the button will pressed
        [sender setImage:unfollowImageHighlighted forState:UIControlStateHighlighted];
    } else {
        // set this image for the next time the button will pressed
        [sender setImage:followImageHighlighted forState:UIControlStateHighlighted];
    }
}
- (void)viewDidLoad
{
    // ...
    UIImage *followImage = [UIImage imageNamed:@"follow.png"];
    UIImage *unfollowImage = [UIImage imageNamed:@"unfollow.png"];
    [self.followButton setImage:followImage forState:UIControlStateNormal];
    [self.followButton setImage:unfollowImage forState:UIControlStateSelected];
}

问题是,每次按下按钮时,我都会看到高亮显示的图像follow-hilite.png

我不能为路上的按钮更改高亮显示的图像吗?

我认为这是一个糟糕的限制,因为当按钮被选中(因此,"跟随"),用户按下它时,他会看到默认图像,然后当它触摸时,图像是所选状态的图像,当网络操作完成时,按钮图像会正确切换到所选状态。

想法?

编辑

- (IBAction)followButtonTapped:(id)sender
{
    BOOL isFollowed = [sender isSelected];
    NSString *urlString = isFollowed ? kUnfollowURL : kFollowURL;
    // operation [...]
    [self.followButton setSelected:(isFollowed) ? NO : YES];
    self.user.followed = !isFollowed;
}

我更好地解释了这个问题:

  • 按钮处于默认状态:白色背景上的黑色文本
  • 按钮处于选定状态:黑色背景上的白色文本

如果没有关注目标用户,则该按钮处于默认状态,如果我尝试按下它,我会看到正确的高亮显示图像。

但是,如果目标用户被跟踪,并且按钮处于选中状态,如果我尝试按下它(并握住手指),我会看到白色背景上有黑色文本的按钮。这很难看,这是我的问题。

IBAction是配置控件的一个尴尬的地方(往好了说,或者说是不可能的)。你的应用程序中一定有一些条件触发了对不同突出显示图像的要求。在检测到该情况时配置按钮。

使用"按下"回调来执行应用程序应在媒体上执行的任何操作。

我已经用解决了

[myButton setImage:imageSelectedHover forState:(UIControlStateSelected | UIControlStateHighlighted)];

很高兴它能工作。您通过更新应用程序条件解决了这个问题:self.user.flowed。现在,要使它真正正确,请尝试以下操作:

- (IBAction)followButtonTapped:(id)sender
{
    NSString *urlString = self.user.followed? kUnfollowURL : kFollowURL;
    // operation [...]
    self.user.followed = !self.user.followed;
}

模型的状态才是最重要的。按钮的选定状态更像是一个bool,它位于您保存真实后续状态副本的位置。

我认为在尝试修改任何重要内容并计算变量之前,您需要将sender强制转换为UIButton*,因为sender不包含名为-isSelected的方法或属性。试试这个:

- (IBAction)buttonPressed:(id)sender
{
    UIImage *followImageHighlighted = [UIImage imageNamed:@"follow-hilite.png"];
    UIImage *unfollowImageHighlighted = [UIImage imageNamed:@"unfollow-hilite.png"];
    if ([self isSelected]) {
        // set this image for the next time the button will pressed
        [(UIButton*)sender setImage:unfollowImageHighlighted forState:UIControlStateHighlighted];
    } else {
        // set this image for the next time the button will pressed
        [(UIButton*)sender setImage:followImageHighlighted forState:UIControlStateHighlighted];
    }
[self isSelected] = ![self isSelected];
}

最新更新