我创建了一个UIButton子类来为一批按钮添加渐变层,我想知道是否有办法设置按钮的高度,因为它们都是相同的高度。这是我的渐变图层代码,所以我想知道它是否可能以及我需要在代码中放置它的位置:
public class GradientButton: UIButton {
override public func layoutSubviews() {
super.layoutSubviews()
createGradientBackground()
}
func createGradientBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.layer.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.insertSublayer(gradientLayer, atIndex: 0)
}
}
答案 0 :(得分:2)
当然,只需添加:
init() {
self.frame.size.height = 50.0
//Do other stuff you may want
}
OR:
func createGradientBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.layer.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.insertSublayer(gradientLayer, atIndex: 0)
//set custom height wanted
self.frame.size.height = 50.0
}
您可以在自定义init()或createGradientBackground()内部执行此操作。但是,您必须记住在故事板中对按钮设置的约束。
答案 1 :(得分:1)
最简单的方法是覆盖var intrinsicContentSize: CGSize
。
示例:
open class AMPrimaryButton: UIButton {
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.height = 50
return size
}
}
答案 2 :(得分:0)
如果按钮具有自动布局,则可以按以下方式更新约束运行时:
import UIKit
class CustomButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupConstraints()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupConstraints()
}
func setupConstraints() {
NSLayoutConstraint.activate([
self.heightAnchor.constraint(equalToConstant: 50)
])
}
override class var requiresConstraintBasedLayout: Bool {
return true
}
}
在这里您必须设置requiresConstraintBasedLayout
。
如果自定义视图无法使用自动调整大小正确地布局,则应覆盖此属性以返回true。
希望它对您有帮助。