我已经创建了插座和动作。我已将代码链接到用户界面。
当按下按钮时,我希望该按钮被突出显示。这是我编写的代码:
@IBAction func buttonPressed(_ sender: UIButton) {
sender.setTitleColor(UIColor(GL_GREEN), for: .highlighted)
}
我已经创建了插座和动作。我已将代码链接到用户界面。
当按下按钮时,我希望该按钮被突出显示。这是我编写的代码:
@IBAction func buttonPressed(_ sender: UIButton) {
sender.setTitleColor(UIColor(GL_GREEN), for: .highlighted)
}
你可以创建一个UIButton的子类。创建一个新的swift文件并将其命名为您想要的任何名称,但在本例中我将其命名为HighlightedButton。在您创建的新文件中添加以下代码。该类与您创建的文件同名。
import UIKit
class HighlightedButton: UIButton {
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? .red : .green
}
}
}
下一步是将 HighlightedButton 设置为您的按钮类:
在故事板中选择要更改的 UIButton。 在标识检查器中,右上角有一个名为“class”的字段,在那里输入“HighlightedButton”,然后按Enter键。 现在,当您突出显示按钮时,它会变为红色,并在释放按钮时恢复为绿色。
您可以更改为任何颜色。
你需要执行两个动作,一个是“Touch down”,另一个是“Touch up inside”动作。为这两个动作分别更改背景颜色,你就能够实现你的目标。
在2021年...
你只需要将ButtonType设置为“ .system”,它将在按下时突出显示。
let button = UIButton(type: .system)
lazy var myButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Show More", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
return button
}()
@objc fileprivate func buttonTapped() {
//code for segue
}