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

时间:2012-04-03 21:49:37

标签: iphone objective-c cocoa-touch 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;
}

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

    默认状态下的
  • 按钮:白色背景上的黑色文字
  • 选择状态下的
  • 按钮:黑色背景上的白色文字

如果未跟踪目标用户,则该按钮处于默认状态,如果我尝试按下该按钮,则会看到正确的突出显示图像。

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

4 个答案:

答案 0 :(得分:1)

IBAction是配置控件的尴尬(最好或不可能)的地方。您的应用中必须有一些条件触发对不同突出显示图像的要求。检测到该情况时配置按钮。

使用“按下”回调来执行应用在媒体上应采取的任何操作。

答案 1 :(得分:1)

我已经解决了:

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

答案 2 :(得分:1)

很高兴它有效。您通过更新应用程序条件解决了这个问题:self.user.followed。现在,为了使它真的正确,试试这个:

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

模型的状态在这里很重要。按钮的选定状态更像是一个布尔,它位于您保留真实跟随状态的副本的位置。

答案 3 :(得分:0)

我认为您需要在尝试修改任何重要内容之前将发件人转换为UIButton *并计算出您的变量,因为发件人 包含一个名为的方法或属性-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];
}
相关问题