【问题标题】:UIButton changes image created in code when in highlighted stateUIButton 在高亮状态下更改代码中创建的图像
【发布时间】:2014-08-28 04:51:34
【问题描述】:

我有两个按钮。除了其中一个图像被翻转之外,它们都具有相同的图像。如果可以以编程方式创建图像,我不想在我的应用程序包中包含多余的图像,所以我创建这样的按钮:

UIImage *forwardImage = [UIImage imageNamed:rewind_btn_img];
UIImage *rewindImage  = [UIImage imageWithCGImage:forwardImage.CGImage
                                            scale:forwardImage.scale
                                      orientation:UIImageOrientationUpMirrored];

NSArray *images = @[rewindImage, forwardImage];

for (int i = 0; i < 2; i++)
{
    UIButton *btn   = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage  *image = images[i];
    btn.frame       = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
    btn.center      = CGPointMake(self.playButton.center.x + (i == 0 ? - 80.f : 80.f) * TGScaleMultiplier, self.playButton.center.y);
    btn.tag         = i + 1;
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(rewindButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

问题是当我按下图像为rewindImage 的按钮时,它会显示原始图像,并翻转到另一侧。我在这里做错了吗?有什么解决办法吗?

【问题讨论】:

    标签: ios objective-c uibutton uiimage uikit


    【解决方案1】:

    如果它最初看起来是正确的,但当你按下它时会发生变化,请尝试为所有按钮状态设置图像,或者至少为正常状态和选定状态设置图像。

    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn setBackgroundImage:image forState:UIControlStateSelected];
    

    您也可以尝试设置 showsTouchWhenHighlited 但第一种方法应该可以工作

    [btn setShowsTouchWhenHighlighted:NO];
    

    编辑:也尝试设置高亮状态,这对我有用

    [btn setBackgroundImage:image forState:UIControlStateHighlighted];
    

    【讨论】:

    • 不幸的是它没有帮助。按下时仍会翻转到另一侧
    • 调整答案以添加要设置的突出显示状态。这适用于我的代码
    【解决方案2】:

    不确定为什么 UIImage:imageWithCGImage 是片状的,但我尝试了另一种镜像图像的方法,当应用于按钮时效果很好。所以摆脱 UIImage:imageWithCGImage 线并使用这个:

    UIImage *rewindImageBase = [UIImage imageNamed:rewind_btn_img];
    UIGraphicsBeginImageContext(rewindImageBase.size);
    CGContextRef current_context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(current_context, rewindImageBase.size.width, 0);
    CGContextScaleCTM(current_context, -1.0, 1.0);
    [rewindImageBase drawInRect:CGRectMake(0, 0, rewindImageBase.size.width, rewindImageBase.size.height)];
    UIImage *rewindImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    应该可以的。

    【讨论】:

    • 当您的回答有效并且实际上回答了我无法接受的问题时。以您提议的方式创建的图像看起来更糟。它不准确,它看起来很模糊。无论如何,谢谢,我对你的答案投了赞成票
    • 哦,当我测试它时,我没有注意到这一点。您还可以为 UIControlStateSelected 设置按钮状态并调整所选图像的 alpha。绝对让我摸不着头脑,为什么那种情绪低落的状态如此奇怪。谢谢!
    猜你喜欢
    • 2011-11-29
    • 2012-08-17
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2017-04-22
    • 2015-03-26
    相关资源
    最近更新 更多