创建约束以在以编程方式调整大小的视图上重新定位按钮

Create Constraints to reposition the button on the view resized programmatically

我正在开发一款可以调整形状大小的应用程序。例如,我正在使用视图。

我画了我的看法:

并以编程方式创建了一个按钮并添加了一个 UIPanGestureRecognizer:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var rect: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let rectFrame = rect.frame
        let selectorColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 0.700)

        let resizeTopLeft = UIButton(frame: CGRect(x: rectFrame.size.width - 20, y: rectFrame.size.height - 20, width: 20, height: 20))
        resizeTopLeft.backgroundColor = selectorColor

        let panTopLeft = UIPanGestureRecognizer(target: self, action: "panTopLeft:")
        resizeTopLeft.addGestureRecognizer(panTopLeft)

        rect.addSubview(resizeTopLeft)
    }

    func panTopLeft(gesture: UIPanGestureRecognizer){
        let location = gesture.locationInView(rect)
        rect.frame.size = CGSize(width: location.x + 20, height: location.y + 20)
    }
}

在运行时,呈现如下:

当跨屏按钮移动时,视图会按预期调整大小。但是按钮还在同一个地方。

这就是问题所在:我需要你在按钮定位为约束时调整视图大小。我试着做了几个约束,但都没有达到预期的效果。

我的问题:如何创建约束以重新定位以编程方式调整大小的视图上的按钮

这里你应该使用自动布局。否则,您还应该在平移手势选择器中设置按钮的位置。

这是我的自动布局解决方案。

第 1 步: 为您的视图添加前导、顶部、宽度和高度约束。像

第 2 步: 通过 IBOutlet 连接宽度和高度约束。喜欢

 @IBOutlet weak var rectHeightConstraint: NSLayoutConstraint!
 @IBOutlet weak var rectWidthConstraint: NSLayoutConstraint!

第 3 步: 添加具有自动布局约束的按钮

    //Create UIButton
    let selectorColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 0.700)
    let resizeTopLeft = UIButton()
    resizeTopLeft.backgroundColor = selectorColor
    resizeTopLeft.translatesAutoresizingMaskIntoConstraints = false

    //Add gesture recognizer
    let panTopLeft = UIPanGestureRecognizer(target: self, action: "panTopLeft:")
    resizeTopLeft.addGestureRecognizer(panTopLeft)

    rect.addSubview(resizeTopLeft)

    //Add auto layout constraints for the button
    let views = ["resizeTopLeft" : resizeTopLeft]

    let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:[resizeTopLeft(20)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
    self.rect.addConstraints(horizontalConstraints)

    let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[resizeTopLeft(20)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
    self.rect.addConstraints(verticalConstraints)

第 4 步: 更新平移手势方法中的高度和宽度约束。

func panTopLeft(gesture: UIPanGestureRecognizer) {
    let location = gesture.locationInView(rect)
    //To avoid zero sized view.
    if (location.y < 0) || (location.x < 0) {
        return
    }
    rectHeightConstraint.constant = location.y + 20
    rectWidthConstraint.constant = location.x + 20
}