繁体   English   中英

创建约束以以编程方式调整视图上按钮的位置

[英]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)
    }
}

在运行时,它显示如下:

在此处输入图片说明

当在屏幕按钮上移动时,视图将按预期调整大小。 但是按钮仍在同一位置。

这就是问题所在: 当按钮定位为Constraints时,我需要您调整视图的大小 我试图做出一些约束,但没有达到预期效果。

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

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

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

步骤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
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM