gpt4 book ai didi

ios - 防止可拖动 View 离开屏幕

转载 作者:搜寻专家 更新时间:2023-11-01 06:36:24 25 4
gpt4 key购买 nike

我有一个可拖动的按钮,但我不希望用户能够拖动 View ,这样两侧就会被屏幕边缘截断。

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self.superview)

self.center = CGPoint(x: position.x, y: position.y)

}

}

我这样做的方式是大量的 if/else 语句检查屏幕上的允许区域。

 let halfOfButton = CGFloat(85 / 2)
let heightOfTopBar = CGFloat(55) + halfOfButton
let widthOfScreen = CGFloat((self.superview?.frame.width)!) - halfOfButton
let heightOfScreen = CGFloat((self.superview?.frame.height)!) - heightOfTopBar

let heightOfBotBar = CGFloat((self.superview?.frame.height)! - heightOfTopBar)


if position.x > halfOfButton && position.x < widthOfScreen {
self.center = CGPoint(x: position.x, y: position.y)

} else {
if position.x < halfOfButton {
self.center = CGPoint(x: halfOfButton, y: position.y)
} else {
self.center = CGPoint(x: widthOfScreen, y: position.y)
}
}

if position.y > heightOfTopBar && position.y < heightOfScreen && position.x > halfOfButton && position.x < widthOfScreen {
self.center = CGPoint(x: position.x, y: position.y)

} else {
if position.y < heightOfTopBar {
self.center = CGPoint(x: position.x, y: heightOfTopBar)
} else {
self.center = CGPoint(x: position.x, y: heightOfScreen)
}
}
}

有没有更好的方法来实现这一点?上面的代码甚至还不能完全工作。它在逻辑上有很多缺陷,我说“如果 Y 没问题,那么就让你的触摸中心成为按钮的中心”,但这会覆盖我在 X 中编写的代码即使 Y 可能没问题,但 X 却不行。

我可以通过这种方式将其逻辑化,但肯定有更好的方法吗?

最佳答案

尝试这样的事情:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self.superview)

var x:CGFloat = position.x
var y:CGFloat = position.y

let parentWidth = button.superView!.frame.size.width
let parentHeight = button.superView!.frame.size.height

let width = button.frame.size.width / 2
let height = button.frame.size.height / 2

x = max(width, x)
x = min(x, parentWidth - width)

y = max(height, y)
y = min(y, parentHeight - height)



self.center = CGPoint(x: x, y: y)

}

关于ios - 防止可拖动 View 离开屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091551/

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