您的视图快速增长的原因是您始终使用自第一次触摸以来移动的距离更新当前视图高度。您应该始终添加移动到视图原始高度的距离,而不是修改当前高度。
将另一个属性添加到您的自定义视图以跟踪视图的原始高度。将其设置为touchesBegan
,然后在touchesMoved
计算帧时使用originalHeight
:
class CustomView: UIView {
var startPosition: CGPoint?
var originalHeight: CGFloat = 0
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
startPosition = touch?.locationInView(self)
originalHeight = self.frame.height
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let endPosition = touch?.locationInView(self)
let difference = endPosition!.y - startPosition!.y
let newFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.width, originalHeight + difference)
self.frame = newFrame
}
}
为什么约束不改变帧申请后,如何重新申请 呢?
使用自动布局时,您确实不应该更新帧。正确的做法是将@IBOutlet
添加到视图的高度约束中,然后在您希望更改视图的高度时更新约束的constant
属性。
当您这样做时,自动布局将使用更新的高度正确定位自定义视图的子视图。
要将@IBOutlet
从高度约束在文档大纲添加到高度约束你的代码,控制 -drag您的viewController。给它起个名字,如customViewHeight
。
![Control drag to create @IBOutlet for height constraint](https://i.stack.imgur.com/dia1g.png)
由于您更新视图的高度代码视图代码本身,有指定的viewController的高度约束到自定义视图viewDidLoad
。然后,自定义视图可以更新高度约束的constant
属性以调整视图的大小。
class ViewController: UIViewController {
@IBOutlet weak var customViewHeight: NSLayoutConstraint!
@IBOutlet weak var customView: CustomView!
override func viewDidLoad() {
super.viewDidLoad()
// Assign the layout constraint to the custom view so that it can update it itself
customView.customViewHeight = customViewHeight
}
}
class CustomView: UIView {
var startPosition: CGPoint?
var originalHeight: CGFloat = 0
var customViewHeight: NSLayoutConstraint!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
startPosition = touch?.locationInView(self)
originalHeight = customViewHeight.constant
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let endPosition = touch?.locationInView(self)
let difference = endPosition!.y - startPosition!.y
customViewHeight.constant = originalHeight + difference
}
}