我正在开发一款调整形状大小的应用。我以视图为例。
我画了我的观点:
以编程方式创建了一个按钮,并添加了一个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)
}
}
在运行时,它显示如下:
当移动屏幕按钮时,视图会按预期调整大小。但按钮仍然在同一个地方。
这就是问题:当按钮被定位为约束时,我需要你调整视图的大小。我尝试制作了几个约束,没有按预期工作。
我的问题:如何创建约束以重新定位以编程方式调整大小的视图?
答案 0 :(得分:1)
在这里你应该使用自动布局。否则你也应该在t pan手势选择器中设置按钮的位置。
这是我的自动布局解决方案。
第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
}