您的视图快速增长的原因是您始终根据自第一次触地以来移动的距离更新当前视图高度。不要修改当前高度,您应该始终添加移动到视图原始高度的距离。
向您的自定义视图添加另一个属性以跟踪视图的原始高度。将其设置为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 添加到代码的高度约束,Control-从 Document Outline 中的高度约束拖动到 viewController。给它起一个名字,例如customViewHeight。
由于更新视图高度的代码位于视图代码本身中,因此请让 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
}
}