所以我有下面的按钮,当点击时只会在标题中添加渐变动画。我希望渐变动画发生在整个按钮中。我该怎么做?谢谢
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let button = UIButton(type: .system)
button.setTitle("Btn", for: .normal)
button.backgroundColor = .systemBlue
button.tintColor = .white
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.heightAnchor.constraint(equalToConstant: 60.0),
button.widthAnchor.constraint(equalToConstant: 60.0),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
您可以尝试将addTarget与objc函数一起使用:
@objc func buttonTapped(_ sender: UIButton){
print("buttonTapped")
sender.alpha = 0.5
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
sender.alpha = 1.0
}
}
通过执行
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)