나는 드래그 가능한 버튼을 가지고 있습니다. 사용자가 화면을 드래그하여 화면의 가장자리가 잘리지 않도록하고 싶습니다.draggable 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는 그렇지 않습니다.
이 방법으로 논리를 추출하는 것이 가능하지만 확실한 방법은이 방법을 사용하는 것입니다. 이 같은
전에 최소/최대 내용을 보지 못했습니다. 완벽하게 작동합니다. 감사합니다! – user6820041