gpt4 book ai didi

ios - 如何防止 View 在捏合手势上超出其父边界 - swift

转载 作者:可可西里 更新时间:2023-11-01 00:51:59 27 4
gpt4 key购买 nike

我将捏合手势分配给了 uiview:

myView.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: "handlePinch:"))

此函数将缩放 uiview:

func handlePinch(recognizer : UIPinchGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform,
recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}

但比例在父 View 内不受限制。当我尝试缩小它时,它也没有限制,它会一直缩放直到消失。

灰色 View 是父 View

Desciption

我的问题

如何防止放大时超出父框架,缩小时消失?

最佳答案

你可以使用这样的东西:

if let view = recognizer.view, parent = recognizer.view.superview {

// this will only let it scale to half size
let minimumThreshold: CGFloat = 0.5
var scale: CGFloat = recognizer.scale

// assuming your view is square, which based on your example it is
let newSize = view.frame.height * scale

// prevents the view from growing larger than the smallest dimension of the parent view
let allowableSize = min(parent.frame.height, parent.frame.width)
let maximumScale: CGFloat = allowableSize/view.frame.height

// change scale if it breaks either bound
if scale < minimumThreshold {
print("size is too small")
scale = minimumThreshold
}

if newSize > allowableSize {
print("size is too large")
scale = maximumScale
}

// apply the transform
view.transform = CGAffineTransformMakeScale(scale, scale)
}

此处的关键是根据偏好确定下限,并根据 View 的初始大小与父 View 大小的比率确定上限。通过这样做, View 不能缩小到比期望的更小,因为假设用户不应该能够缩小到由于难以捏合而无法调整大小的点。此外,不应允许 View 无限缩放,从而溢出其边界。此检查就是这样做的,因为它只允许您指定由用户交互设置的尺寸范围。

关于ios - 如何防止 View 在捏合手势上超出其父边界 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34482064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com