ios - UIButton 函数添加点击样式

标签 ios swift uibutton

我在 Swift 4 中编写了一个函数,它创建了一个按钮,该按钮接收 UIButton、一个颜色和一个字符串作为标题。我想为此功能添加一个突出显示或点按样式,但我不确定如何操作。

函数:

 func homeBtn(button: UIButton, color: UIColor, title: String){
    button.setTitle(title, for: .normal)
    button.setTitleColor(color, for: .normal)
    button.titleLabel?.font =  UIFont(name: "Raleway-Medium", size: 24)
    button.titleLabel?.lineBreakMode = .byWordWrapping
    button.titleLabel?.textAlignment = .center
    button.titleEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
    button.layer.borderColor = color.cgColor
    button.layer.borderWidth = 2
    button.layer.cornerRadius = button.frame.width/2
    button.layer.backgroundColor = whiteColor.cgColor
 }

按钮是一个圆圈,中间有一个字符串,UIColor 用作轮廓。有人可以告诉我如何向使用相同 UIColor 填充按钮并将文本变为白色的此功能添加点击样式吗?

最佳答案

对于标题颜色,您无需添加事件即可轻松做到这一点。

button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.black, for: .normal)

对于背景颜色,您需要定义以下事件:

    button.addTarget(self, action: #selector(touchDown(button:)), for: .touchDown)
    button.addTarget(self, action: #selector(touchUpInside(button:)), for: .touchUpInside)

定义函数 - 您也可以引用其他触摸类型 - 请参阅 UIControlEvents

@objc func touchDown(button: UIButton) {
    guard let borderColor = button.layer.borderColor else {
        return
    }
    button.backgroundColor = UIColor(cgColor: borderColor)
}

@objc func touchUpInside(button: UIButton) {
    // Set backgroundColor for normal state...
}

关于ios - UIButton 函数添加点击样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286074/

相关文章:

iphone - UIButton 的图像与背景图像

ios - 添加应用组后 Xcode 显示警告(将 "App Groups"授权添加到您的应用 ID)

ios - Restkit:重试失败的请求

Swift 闭包真的可以修改常量吗?

swift - Swift 中的四舍五入整数

ios - 使用 AutoLayout 创建顶部有图像、底部有标签的 UIButton (UIButtonTypeCustom)

objective-c - 关联 UIButton

ios - SiriKit 付款确认货币始终为美元

ios - Cocos2d 游戏在 CCCallFunc 后不久崩溃

arrays - 如何从打印中删除 () (swift3)