-1
我想在iOS项目的图片中定义可点击区域。 它看起来像“沃利在哪里”。当我点击特定区域时,Swift会执行此操作。 也有刷卡管理。 我想做一个透明的按钮,但我不知道是否有可能..如何在Swift中定义图片中的区域3
你有什么想法吗?
谢谢! :-)
我想在iOS项目的图片中定义可点击区域。 它看起来像“沃利在哪里”。当我点击特定区域时,Swift会执行此操作。 也有刷卡管理。 我想做一个透明的按钮,但我不知道是否有可能..如何在Swift中定义图片中的区域3
你有什么想法吗?
谢谢! :-)
在iOS设备上,你可以这样说:
(1)一定要设置你的UIImageView接收用户交互,并添加UITapGestureRecognizer到UIImageView的。
myImageView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer()
tapGesture.numberOfTapsRequired = 1
tapGesture.addTarget(self, action: #selector(tapDetected())
(2)创建一个新的CALayer,它的大小,它的位置,并把它添加到的UIImageView的层。
let tappableLayer = CALayer() // place this as a global variable
tappableLayer.frame = // give a CGRect size here, or you can make it a shape by declaring a UIBezierPath and making it a CAShapeLayer
myImageView.layer.addSublayer(tappableLayer)
(3)代码的tapDetected功能。
func tapDetected(_ recognizer:UITapGestureRecognizer) {
let p = recognizer.location(in: self)
if tappableLayer.hitTest(p) != nil {
// user tapped in your defined area of the image
}
}
不错的答案。我首先想知道为什么你使用CALayer而不是简单的CGRect,但是有可能为'hitTest'使用不同的形状是非常棒的! – Kie
hitTest()方法属于* all * CALayers。如果您只是为myImageView图层打开它,则会检测整个视图。所以我不使用CGRect的另一个原因是因为它没有hitTest()方法。 – dfd
1.我不明白这与我对你的回答的恭维有什么关系,而是真实的故事! :) 2.我可以使用'CGRectContainsPoint'。 – Kie