将按钮绑定到iOS swift视图的右上角

时间:2016-05-20 09:29:06

标签: ios xcode swift layout

我有一个视图,其中我有多个标签enter image description here和一个按钮,我希望按钮被绑定到右上角

当我应用添加缺失约束布局时,按钮会为不同设备分别位置请帮我解决此问题

2 个答案:

答案 0 :(得分:7)

永远不要使用add missing constraints。这是构建布局的一种不好的方法。

获得理想外观的最简单方法是决定按钮所需的尺寸(例如30x30)

然后将以下约束添加到按钮:

这会设置按钮的宽度和宽度。高度:

enter image description here

然后将其固定在右上角:

enter image description here

答案 1 :(得分:2)

enter image description here //万一有人需要代码:

//I have added 4 buttons to a custom view's each corner:

var customView = UIView()

 override func viewDidLoad() {
        super.viewDidLoad()

        customView.frame = CGRect.init(x: 0, y: 0, width: 200, height: 200)
        customView.backgroundColor = UIColor.red     //give color to the view
        customView.center = self.view.center

        let crossButton = UIButton(frame: CGRect(x: -10, y: -10, width: 30, height: 30))
        crossButton.layer.cornerRadius = 15
        crossButton.backgroundColor = UIColor.black
        crossButton.setImage(UIImage(named: "cross.png"), for: .normal)
        crossButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
        crossButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]


        let flipButton = UIButton(frame: CGRect(x: customView.frame.width-15, y: -10, width: 30, height: 30))
        flipButton.layer.cornerRadius = 15
        flipButton.backgroundColor = UIColor.black
        flipButton.setImage(UIImage(named: "done.png"), for: .normal)
        flipButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
        flipButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]

        let scaleButton = UIButton(frame: CGRect(x: -10, y: customView.frame.height-20, width: 30, height: 30))
        scaleButton.layer.cornerRadius = 15
        scaleButton.backgroundColor = UIColor.black
        scaleButton.setImage(UIImage(named: "done.png"), for: .normal)
        scaleButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
        scaleButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]

        let editButton = UIButton(frame: CGRect(x: customView.frame.width-20, y: customView.frame.height-20, width: 30, height: 30))
        editButton.layer.cornerRadius = 15
        editButton.backgroundColor = UIColor.black
        editButton.setImage(UIImage(named: "done.png"), for: .normal)
        editButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
        editButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]

        customView.addSubview(crossButton)
        customView.addSubview(flipButton)
        customView.addSubview(scaleButton)
        customView.addSubview(editButton)

        self.view.addSubview(customView)

    }

    func crossButtonTapped(_ sender:UIButton) {

        print("Cross Button was tapped")
    }