【问题标题】:Add button to right side of screen将按钮添加到屏幕右侧
【发布时间】:2019-03-13 22:03:54
【问题描述】:

我在屏幕左侧添加了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)
    }

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

【问题讨论】:

  • 方法相同,但origin.x 值不同。
  • @rmaddy - origin: CGPoint.zero 是 0,0。右侧怎么做?
  • 将第一个 0 更改为所需的号码,以便在您想要的位置。更好的是,使用约束。
  • @rmaddy 如何编辑第一个 0?我应该从CGPoint.zero 更改为CGPoint(x: screenSize.width-44, y: 0) 吗?
  • 使用约束。比编码帧要好得多。

标签: ios swift uibutton


【解决方案1】:

你可以试试

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)
])      

【讨论】:

    【解决方案2】:

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

    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)
    }
    

    【讨论】:

    • 您不应该根据屏幕大小做任何事情。它基于视图控制器视图的大小。使用约束会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2015-03-17
    • 2017-08-17
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    相关资源
    最近更新 更多