gpt4 book ai didi

iOS:无法检测到 CALayer 边界外的触摸

转载 作者:行者123 更新时间:2023-11-28 06:15:04 25 4
gpt4 key购买 nike

我正在创建一个可重复使用的多状态开关,该开关从 UIControl 扩展而来,它看起来类似于默认的 UISwitch,具有两个以上的状态。实现就像为每个状态添加 CALayers 和一个额外的 Layer 来突出显示 UIView 上的选定状态。

界面是这样的

multi state switch

问题是,当用户点击图片中所示的方形边框外时,我无法识别触摸状态。在给定触摸点的情况下,我添加了一个简单的便捷方法 (getIndexForLocation) 来返回选定状态的索引。使用返回的选定索引,我将突出显示指示器的位置移动到选定状态的中心。

func getIndexForLocation(_ point: CGPoint) -> Int {
var index = selectedIndex
let sLayers = self.controlLayer.sublayers
for i in 0..<totalStates {
if sLayers![i].frame.contains(point) {
index = i
}
}
return index
}

上述方法是从具有最后一个触摸点的 UIControl 的 endTracking(touch:for event) 方法调用的。

如何更改此方法,以便即使用户触摸了图像,我也可以获得触摸/选择状态的索引。触摸区域可以近似为状态图像中心上方的高亮圆圈区域。

self.controlLayer 是容器层,其子层是所有状态和高亮指示器。

下面提供了添加选择索引做定位动画的方法

func performSwitch(to index: Int) -> () {
guard selectedIndex != index else {
return
}

let offsetDiff = CGFloat((index - selectedIndex) * (stateSize + 2))
let oldPosition = indicatorPosition
indicatorPosition.x += offsetDiff
let newPosition = indicatorPosition

let animation: CABasicAnimation = CABasicAnimation(keyPath: "position")
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.785, 0.135, 0.15, 0.86)
animation.duration = 0.6
animation.fromValue = NSValue(cgPoint: oldPosition!)
animation.toValue = NSValue(cgPoint: newPosition!)
animation.autoreverses = false
animation.delegate = self
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards


self.selectedIndex = index
self.stateIndicator.add(animation, forKey: "position")
}

如有任何帮助,我们将不胜感激。

最佳答案

你通过说 if sLayers![i].frame.contains(point) 来测试。因此,最简单的解决方案是使每个“按钮”的框架大得多——大到足以包含您希望像这个“按钮”一样可触摸的整个区域。请记住,即使框架很大,绘图也可以很小。

此外,顺便说一句,您的代码很愚蠢,因为您基本上是在执行 HitTest 。层的 HitTest 是内置的,所以一旦你的框架正确,你所要做的就是调用 hitTest(_:)在超层上。这会告诉您哪一层被窃听了。

(当然,使用 subview 而不是图层会更好。 View 可以检测触摸;图层不能。)

关于iOS:无法检测到 CALayer 边界外的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45403153/

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