Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 自定义UIButton类未水平居中_Swift_Xcode_Uibutton_Storyboard_Viewcontroller - Fatal编程技术网

Swift 自定义UIButton类未水平居中

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

我创建了一个自定义按钮类,它覆盖Xcode中的默认按钮外观。我将我现有的故事板按钮类指定给新的自定义类,除了按钮不再水平居中外,其他一切看起来都很好。我不熟悉Swift编码,非常感谢您的帮助

以前

之后

以下是自定义按钮类代码:

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位置约束。