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

Simple way to show to the user that he pressed a button by changing the background color?

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

我们可以使用界面生成器中的 shows touch on highlight,但它并不能真正满足我的需求。

在我的 table 视图中,我是通过在 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

中调用 tableView.deselectRowAtIndexPath(indexPath, animated: true) 来做到这一点的

是否有类似的简单方法,或者我是否必须通过 button.layer.backgroundColor 动画更改按钮的背景颜色?

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

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

+ (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];

Swift 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
    }
}