在屏幕右侧添加按钮

时间:2019-03-13 22:03:55

标签: ios swift uibutton

我在屏幕左侧添加了UIButton。我这样添加它:

let screenSize: CGRect = UIScreen.main.bounds
let menuButtonSize: CGSize = CGSize(width: 44, height: 44)
func confiureCloseButton() {
        let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: menuButtonSize))
        button.setImage(UIImage(named: "icon_close"), for: UIControl.State.normal)
        button.center = CGPoint(x: 50, y: 61)
        button.layer.zPosition = 1
        button.addTarget(self, action: #selector(closeButtonAction), for: .touchUpInside)

        self.view.addSubview(button)
    }

如何在右侧添加另一个按钮?

2 个答案:

答案 0 :(得分:0)

您可以尝试

firstBu.translatesAutoresizingMaskIntoConstraints = false 
self.view.addSubview(firstBu)  
secondBu.translatesAutoresizingMaskIntoConstraints = false 
self.view.addSubview(secondBu)  
NSLayoutConstraint.activate([ 
    firstBu.leadingAnchor.constraint(equalTo: self.view.leadingAnchor,constant:50), 
    firstBu.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor,constant:61), 
    firstBu.widthAnchor.constraint(equalToConstant: 44), 
    firstBu.heightAnchor.constraint(equalToConstant: 44),  
    secondBu.leadingAnchor.constraint(equalTo: self.firstBu.trailingAnchor,constant:20), 
    secondBu.centerYAnchor.constraint(equalTo: self.firstBu.centerYAnchor), 
    secondBu.widthAnchor.constraint(equalToConstant: 44), 
    secondBu.heightAnchor.constraint(equalToConstant: 44)
])      

答案 1 :(得分:-1)

假设您希望按钮成为左按钮的镜像:

func configureRightButton() {
    let rightButton = UIButton(frame: CGRect(origin: CGPoint.zero, size: menuButtonSize))
    let frameWidth = view.frame.width

    rightButton.center = CGPoint(x: frameWidth - 50, y: 61)
    rightButton.layer.zPosition = 1

    view.addSubview(rightButton)
}