如何在 SwiftUI + iPadOS 上使用自定义鼠标指针?
苹果提供了一个示例代码,但是该代码适用于 UIKit: https://developer.apple.com/documentation/uikit/pointer_interactions/enhancing_your_ipad_app_with_pointer_interactions
class QuiltView: UIView, UIPointerInteractionDelegate {
...
func sharedInit() {
...
// Add a pointer interaction for the "editor" area Quilt view.
self.addInteraction(UIPointerInteraction(delegate: self))
}
// Supply custom regions that correspond to grid lines when "useStraightLineStitch" is enabled.
func pointerInteraction(_ interaction: UIPointerInteraction,
regionFor request: UIPointerRegionRequest,
defaultRegion: UIPointerRegion) -> UIPointerRegion? {
if useStraightLineStitch {
let regionNumber = floor(request.location.y / gridHeight)
return UIPointerRegion(rect: CGRect(x: 0, y: regionNumber * gridHeight, width: self.bounds.size.width, height: gridHeight))
} else {
return defaultRegion
}
}
// Supply pointer style with custom crosshair shape.
func pointerInteraction(_ interaction: UIPointerInteraction, styleFor region: UIPointerRegion) -> UIPointerStyle? {
let crosshair = UIPointerShape.path(crosshairBezierPath())
if useStraightLineStitch {
return UIPointerStyle(shape: crosshair, constrainedAxes: [.vertical])
} else {
return UIPointerStyle(shape: crosshair)
}
}
func crosshairBezierPath() -> UIBezierPath {
let crosshairPath = UIBezierPath()
crosshairPath.move(to: CGPoint(x: -1.5, y: 1.5))
crosshairPath.addLine(to: CGPoint(x: -1.5, y: 10))
crosshairPath.addArc(withCenter: CGPoint(x: 0, y: 10),
radius: 1.5,
startAngle: CGFloat.pi,
endAngle: 0,
clockwise: false)
crosshairPath.addLine(to: CGPoint(x: 1.5, y: 1.5))
crosshairPath.addLine(to: CGPoint(x: 10, y: 1.5))
crosshairPath.addArc(withCenter: CGPoint(x: 10, y: 0),
radius: 1.5,
startAngle: CGFloat.pi / 2.0,
endAngle: CGFloat.pi * 1.5,
clockwise: false)
crosshairPath.addLine(to: CGPoint(x: 1.5, y: -1.5))
crosshairPath.addLine(to: CGPoint(x: 1.5, y: -10))
crosshairPath.addArc(withCenter: CGPoint(x: 0, y: -10),
radius: 1.5,
startAngle: 0,
endAngle: CGFloat.pi,
clockwise: false)
crosshairPath.addLine(to: CGPoint(x: -1.5, y: -1.5))
crosshairPath.addLine(to: CGPoint(x: -10, y: -1.5))
crosshairPath.addArc(withCenter: CGPoint(x: -10, y: 0),
radius: 1.5,
startAngle: CGFloat.pi * 1.5,
endAngle: CGFloat.pi / 2.0,
clockwise: false)
crosshairPath.close()
return crosshairPath
}
...
我希望使用SwiftUI实现相同的功能,您能帮忙翻译吗?
提前感谢。
UIPointerInteraction(delegate:)
调用应该可以工作。(2) 除非你将其添加到UIKit中的特定对象,比如UITextField或UITableView,否则很难进行内省。如果你只是寻找一个UIView,很容易得到错误的视图,或者一个没有宽度/高度的视图。 - Josh Hrach