通过更改背景颜色向用户显示他按下按钮的简单方法?

Posted

技术标签:

【中文标题】通过更改背景颜色向用户显示他按下按钮的简单方法?【英文标题】:Simple way to show to the user that he pressed a button by changing the background color? 【发布时间】:2015-03-16 07:42:09 【问题描述】:

我想,当用户按下按钮时,给他一个他按下按钮的反馈,例如背景颜色的快速动画变化(例如,比按钮背景颜色更浅的颜色)。

我们可以使用 Interface builder 中的 shows touch on highlight,但它并不能真正满足我的要求。

在我的表格视图中,我通过在func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 中调用tableView.deselectRowAtIndexPath(indexPath, animated: true) 来做到这一点

是否有类似的简单方法可以做到这一点,还是我必须通过button.layer.backgroundColor 用动画更改按钮的背景颜色?

【问题讨论】:

我刚刚看到我正在寻找的东西可以通过使用图像来完成。但我很惊讶当你不需要像我这样的图像时,当你有一个只有一种简单颜色的按钮时,这并不简单 如果你使用UIButtonTypeSystem,你可以控制按钮的色调颜色。 但是色调如果只是为了它看起来像的字体,不是吗? 图像的色调,或者字体是的。我已经发布了背景颜色的解决方案。 【参考方案1】:

继续我的评论——当你初始化你的按钮时,确保它的类型是UIButtonTypeSystem

然后,您可以借助可以添加到UIImage 类别的此类方法来更改按钮的背景颜色:

+ (UIImage *)imageWithColor:(UIColor *)color     
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0, 1.0);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;

然后,对您的按钮执行此操作:

[button setBackgroundImage:[UIImage imageWithColor:[UIColor greenColor]]
                  forState:UIControlStateHighlighted];

斯威夫特 3:

extension UIImage 
    public class func imageFromColor(_ color: UIColor) -> UIImage? 
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() 
            context.setFillColor(color.cgColor)
            context.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    

【讨论】:

谢谢。它有效,但令我惊讶的是,没有什么比为常见的东西构建方法更容易的了。顺便问一下,你知道使用高亮状态时 backgroundImage 的 alpha 值吗? 我不知道确切的值,但是您可以尝试通过实现它来调试它 - ***.com/a/8702247/3360360(您也可以稍后在代码中使用它来控制按钮的 alpha)。只需在 - if(self.highlighted) NSLog(@"Alpha value: %f", self.alpha); 中打印 alpha 值

以上是关于通过更改背景颜色向用户显示他按下按钮的简单方法?的主要内容,如果未能解决你的问题,请参考以下文章

按下按钮时更改列表视图背景颜色

iOS UIButton(按钮)点击改变背景色和标题颜色的简单实现

按下时更改操作栏按钮的背景颜色

如何使用背景颜色设置圆形按钮并在按下时更改颜色

UIView 背景颜色颜色循环

按下时更改 QPushButton 颜色