Swift 自定义UIButton类未水平居中
我创建了一个自定义按钮类,它覆盖Xcode中的默认按钮外观。我将我现有的故事板按钮类指定给新的自定义类,除了按钮不再水平居中外,其他一切看起来都很好。我不熟悉Swift编码,非常感谢您的帮助 以前 之后 以下是自定义按钮类代码:Swift 自定义UIButton类未水平居中,swift,xcode,uibutton,storyboard,viewcontroller,Swift,Xcode,Uibutton,Storyboard,Viewcontroller,我创建了一个自定义按钮类,它覆盖Xcode中的默认按钮外观。我将我现有的故事板按钮类指定给新的自定义类,除了按钮不再水平居中外,其他一切看起来都很好。我不熟悉Swift编码,非常感谢您的帮助 以前 之后 以下是自定义按钮类代码: import UIKit class CustomButton: UIButton { let radius: CGFloat = 40 let darkGreen: UIColor = UIColor(red: CGFloat
import UIKit
class CustomButton: UIButton {
let radius: CGFloat = 40
let darkGreen: UIColor = UIColor(red: CGFloat(23)/CGFloat(255),
green: CGFloat(165)/CGFloat(255),
blue: CGFloat(137)/CGFloat(255),
alpha: 1)
let lightGreen: UIColor = UIColor(red: CGFloat(112)/CGFloat(255),
green: CGFloat(232)/CGFloat(255),
blue: CGFloat(100)/CGFloat(255),
alpha: 1)
override init(frame: CGRect) {
super.init(frame: frame)
setupButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupButton()
}
lazy var gradient: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.type = .axial
gradient.colors = [darkGreen.cgColor, lightGreen.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 0)
gradient.cornerRadius = radius
return gradient
}()
func setupButton() {
frame.size = CGSize(width: 200, height: 80)
tintColor = .white
layer.cornerRadius = radius
gradient.frame = bounds
layer.addSublayer(gradient)
}
}
将以下代码添加到viewController允许我水平居中按钮并指定垂直位置:
mapButton.center = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2.75)
设置约束我向视图控制器添加了以下约束,但它没有将按钮居中,
mapButton.centerXAnchor.constraint(equalTo:view.centerXAnchor.isActive=true
I将约束更改为mapButton.center=view.center
,有效,但是现在两个按钮在屏幕中央重叠,所以看起来我需要找到一种方法为每个按钮指定y位置约束。