UIButton,自定义图像未在所选内容上突出显示

时间:2016-03-27 20:56:16

标签: ios objective-c uibutton

我有透明的图像,我试图在这样的代码中用作UIButton:

        settingsButton = UIButton(type: UIButtonType.Custom)
        settingsButton.translatesAutoresizingMaskIntoConstraints = false
        settingsButton.setImage(UIImage(named: "gear_icon.png"), forState: UIControlState.Normal)
        settingsButton.showsTouchWhenHighlighted = true
        settingsButton.addTarget(self, action: #selector(GameViewController.settingsButtonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(settingsButton)
        let topConstraint = settingsButton.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 10)
        let rightConstraint = settingsButton.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -10)
        NSLayoutConstraint.activateConstraints([topConstraint, rightConstraint])

当我选择按钮时,该按钮不会像标准UIButton那样突出显示。您是否必须为UIControlState.Selected提供自定义图像?我看到了一些代码可以让你通过在这样的代码中创建一个UIImage来提供这种效果:

func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context: CGContextRef = UIGraphicsGetCurrentContext()!
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

但是当我查看一些在IB中使用自定义图像的在线示例项目时,看起来他们没有为UIControlState.Selected设置任何图像,但是当按下按钮时,UIButton的图像变为灰色所以我对如何做到这一点很困惑。

1 个答案:

答案 0 :(得分:0)

我认为您的按钮没有突出显示,因为您自定义了它,我认为您需要为突出显示和按下状态添加图像,或者从UIButtonType将按钮类型从自定义更改为另一种类型然后将图像设置为正常状态,I认为这会有所帮助