我正在开发一款可以调整形状大小的应用程序。例如,我正在使用 View 。
我画了我的观点:
并以编程方式创建一个按钮并添加一个 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)
}
}
在运行时,它呈现如下:
当按钮在屏幕上移动时, View 会按预期调整大小。但是按钮仍然在同一个地方。
这就是问题所在:我需要您在按钮定位为约束时调整 View 大小。我尝试设置了几个约束,但都没有达到预期的效果。
我的问题:如何创建约束以在以编程方式调整大小的 View 上重新定位按钮?
最佳答案
这里你应该使用自动布局。否则,您还应该在平移手势选择器中设置按钮的位置。
这是我的自动布局解决方案。
第一步: 为您的 View 添加前导、顶部、宽度和高度约束。喜欢
第 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
}
关于ios - 创建约束以在以编程方式调整大小的 View 上重新定位按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34348925/