要使用AutoLayout来设置一个渐变按钮,并且不根据高度调整,你可以按照以下步骤进行:
let button = UIButton(frame: CGRect(x: 20, y: 100, width: 200, height: 50))
button.setTitle("Gradient Button", for: .normal)
button.backgroundColor = .blue
let gradientLayer = CAGradientLayer()
gradientLayer.frame = button.bounds
gradientLayer.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
button.layer.insertSublayer(gradientLayer, at: 0)
button.layer.cornerRadius = 10
button.clipsToBounds = true
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
button.widthAnchor.constraint(equalToConstant: 200),
button.heightAnchor.constraint(equalToConstant: 50)
])
完整的示例代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 20, y: 100, width: 200, height: 50))
button.setTitle("Gradient Button", for: .normal)
button.backgroundColor = .blue
let gradientLayer = CAGradientLayer()
gradientLayer.frame = button.bounds
gradientLayer.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
button.layer.insertSublayer(gradientLayer, at: 0)
button.layer.cornerRadius = 10
button.clipsToBounds = true
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
button.widthAnchor.constraint(equalToConstant: 200),
button.heightAnchor.constraint(equalToConstant: 50)
])
view.addSubview(button)
}
}
这样就可以创建一个AutoLayout按钮,它具有渐变的背景并且不会根据高度调整。