如何在中心水平设置按钮

时间:2016-08-12 16:48:47

标签: ios swift button autolayout

我正在尝试以编程方式创建一个按钮,并希望按钮位于底部稍上方,左右空间。目前按钮显示如下

enter image description here

这是代码

func showbutton(){
        let button = UIButton(type: .System) // let preferred over var here
        button.frame = CGRectMake(8, 550, 415, 50)

        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Add new request", forState: UIControlState.Normal)
        //button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
        // Set background color to see if label is centered

        view.addSubview(button)

    }

4 个答案:

答案 0 :(得分:0)

您可以通过调整数字来调整按钮的框架,但是您将失去自动布局功能,当屏幕旋转时,您的按钮看起来不正确。

而是添加约束,就像使用NSLayoutContraint类在故事板中一样。

答案 1 :(得分:0)

这将在左侧和右侧放置8个点的空间,同时保持所有其他尺寸相同

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width

button.frame = CGRectMake(8, 550, screenSize.width-16, 50)

答案 2 :(得分:0)

正如我在评论中提到的,我以编程方式使用AutoLayout(并且您应该使用AutoLayout)是SnapKit

func showbutton(){
    let button = UIButton(type: .System) // let preferred over var here
    button.frame = CGRectMake(8, 550, 415, 50)

    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Add new request", forState: UIControlState.Normal)
    //button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)
    // Set background color to see if label is centered

    view.addSubview(button)
    // create the constraints
    button.snp_makeConstraints { (make) -> Void in
        make.centerY.equalTo(view)
    }
}

答案 3 :(得分:0)

解决方案1:

使用UIView框架作为参考

match

解决方案2:

使用AutoLayout约束:

    import UIKit
    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

            let rect : CGRect = self.view.frame
            let width  = rect.width
            let height = rect.height

            let buttonHeight : CGFloat = 50.0
            let leftMargin : CGFloat = 10.0
            let bottomMargin : CGFloat = 10.0

            let button  : UIButton = UIButton()
            button.frame = CGRectMake(leftMargin, height-buttonHeight-bottomMargin, width - 2*leftMargin , buttonHeight)
            button.backgroundColor = UIColor.greenColor()
            button.setTitle("Add new request", forState: UIControlState.Normal)

            self.view.addSubview(button)
        }
    }

在两种情况下输出相同