如何改变按钮按下和释放时的颜色?

问题描述 投票:0回答:1

我是 Swift 的新手。我想创建一个按钮,当用户按下时该按钮会改变颜色。但是,当用户将手指从按钮上移开时,它应该恢复为原始颜色。

enter image description here

我尝试了教程中显示的不同方法,但没有成功。

swift uikit onpress
1个回答
0
投票

导入UIKit

ViewController 类:UIViewController {

private let button: UIButton = {
    let button = UIButton()
    button.setTitle("First Time", for: .normal)
    button.backgroundColor = UIColor.red
    return button
}()

override func viewDidLoad() {
    super.viewDidLoad()
    button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchDown)
    button.addTarget(self, action: #selector(buttonReleased(_:)), for: [.touchUpInside, .touchUpOutside])
    view.addSubview(button)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let buttonWidth: CGFloat = 200
    let buttonHeight: CGFloat = 50
    button.frame = CGRect(x: (view.bounds.width - buttonWidth) / 2,
                          y: (view.bounds.height - buttonHeight) / 2,
                          width: buttonWidth,
                          height: buttonHeight)
}

@objc func buttonPressed(_ sender: UIButton) {
     sender.backgroundColor = UIColor.blue
 }
@objc func buttonReleased(_ sender: UIButton) {
    sender.backgroundColor = UIColor.red
}

}

© www.soinside.com 2019 - 2024. All rights reserved.