我有一個可拖動的按鈕,我不希望用戶能夠拖動視圖,因此兩邊被屏幕邊緣切斷。防止可拖動的視圖脫離屏幕
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不是。
我可以通過這種方式來理解邏輯,但肯定有更好的方法來做到這一點?
以前沒見過最小/最大的東西。完美的作品,謝謝! – user6820041