以下是我的应用程序的一部分,当您单击屏幕时,它将注册触摸并根据触摸移动到上一张照片或下一张照片。现在,只要您触摸屏幕,它就会注册并移动到上一个或下一个图像。我想限制它,只注册红色方块上的触摸,这样如果你触摸2个红色方块之间的任何东西,就不会发生任何事情。这是我的代码
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self.view)
if location.x < self.view.layer.frame.size.width / 2 {
// touched left side of screen show previous image if exist
}
else {
// touched right side of screen show next
}
}
}
我认为关键是let location = touch.location(in:self.view)然后location.x知道你触摸的宽度位置。我想只注册点击最低10%的屏幕和最亮的10%的屏幕。任何建议都会很棒我正在使用swift 4。
(红色方块仅用于说明。我添加了使用照片编辑功能,它不是应用程序的一部分)
在ViewDidLoad
中,你可以添加两个不可见的UIView
以获得两侧的轻击手势,如下所示,
override func viewDidLoad() {
super.viewDidLoad()
let touchArea = CGSize(width: 80, height: self.view.frame.height)
let leftView = UIView(frame: CGRect(origin: .zero, size: touchArea))
let rightView = UIView(frame: CGRect(origin: CGPoint(x: self.view.frame.width - touchArea.width, y: 0), size: touchArea))
leftView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(leftViewTapped)))
rightView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rightViewTapped)))
leftView.backgroundColor = .clear
rightView.backgroundColor = .clear
self.view.addSubview(leftView)
self.view.addSubview(rightView)
}
@objc func leftViewTapped() {
print("Left")
}
@objc func rightViewTapped() {
print("Right")
}
要么
您可以按如下所示更新当前有问题的方法,以获得所需的结果。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self.view) else { return }
let touchAreaWidth: CGFloat = 80
if location.x <= touchAreaWidth {
print("Left area touched")
} else if location.x >= (self.view.frame.size.width - touchAreaWidth) {
print("Right area touched")
} else {
print("Ignore in-between touch.")
}
}