SwiftUI 还提供了一系列和用户交互、指针行为、视图响应相关的方法。下面是一个分类清单,尤其适用于 macOS 和多平台(macOS + iOS):
一、指针相关(macOS)
1、.onHover {}:检测鼠标是否悬停,适用平台macOS。
2、.hoverEffect(_:):控制悬浮动画效果(仅 iOS),适用平台iOS。
3、.gesture(…):自定义复杂鼠标/触控交互,适用平台通用。
4、.onTapGesture:鼠标单击/触控点击,适用平台通用。
5、.onLongPressGesture:鼠标长按或手指长按,适用平台通用。
6、.onDrag, .onDrop:拖放操作,适用平台macOS / iOS。
二、基础手势(所有平台)
1、.onTapGesture(count:perform:):点击 n 次触发(支持双击)。
2、.onLongPressGesture(minimumDuration:perform:):长按操作。
3、.gesture(…):绑定任意复杂手势(如拖拽、旋转、缩放等)。
三、组合手势
使用 .gesture() 可以组合以下:
1、TapGesture():.gesture(TapGesture().onEnded { }),用于自定义点击。
2、DragGesture():.gesture(DragGesture().onChanged { }),用于拖动。
3、MagnificationGesture():捏合放大缩小。
4、RotationGesture():旋转手势。
5、.simultaneousGesture(…):同时识别多个手势。
四、可用于响应交互的其他常用修饰符
1、.focusable():控制键盘焦点(macOS, tvOS)。
2、.keyboardShortcut(…):支持键盘快捷键。
3、.contextMenu:长按/右键显示上下文菜单。
5、.alert / .confirmationDialog:弹出对话框。
相关文章
1、SwiftUI鼠标悬停onHover:https://fangjunyu.com/2025/07/09/swiftui%e9%bc%a0%e6%a0%87%e6%82%ac%e5%81%9conhover/
2、SwiftUI点击手势onTapGesture:https://fangjunyu.com/2024/12/12/swiftui%e7%82%b9%e5%87%bb%e6%89%8b%e5%8a%bfontapgesture/
3、Swift长按手势onLongPressGesture:https://fangjunyu.com/2024/11/25/swift%e9%95%bf%e6%8c%89%e6%89%8b%e5%8a%bfonlongpressgesture/
4、SwiftUI拖放操作onDrop:https://fangjunyu.com/2025/07/04/swiftui%e6%8b%96%e6%94%be%e6%93%8d%e4%bd%9condrop/
5、SwiftUI拖动操作DragGesture:https://fangjunyu.com/2024/12/13/swiftui%e6%8b%96%e5%8a%a8%e6%93%8d%e4%bd%9cdraggesture/
6、SwiftUI绑定快捷键keyboardShortcut:https://fangjunyu.com/2025/06/19/swiftui%e7%bb%91%e5%ae%9a%e5%bf%ab%e6%8d%b7%e9%94%aekeyboardshortcut/
7、SwiftUI长按手势弹出上下文菜单contextMenu:https://fangjunyu.com/2024/12/10/swift%e4%b8%8a%e4%b8%8b%e6%96%87%e8%8f%9c%e5%8d%95contextmenu/
8、SwiftUI iPad显示浮窗popover:https://fangjunyu.com/2025/01/02/swiftui-ipad%e6%98%be%e7%a4%ba%e6%b5%ae%e7%aa%97popover/
9、Swift弹出sheet视图:https://fangjunyu.com/2024/11/25/swift%e5%bc%b9%e5%87%basheet%e8%a7%86%e5%9b%be/
10、SwiftUI Alert提示框:https://fangjunyu.com/2024/12/07/swift-alert%e6%8f%90%e7%a4%ba%e6%a1%86/
11、Swift上下文菜单式对话框confirmationDialog():https://fangjunyu.com/2024/11/15/swift%e4%b8%8a%e4%b8%8b%e6%96%87%e8%8f%9c%e5%8d%95%e5%bc%8f%e5%af%b9%e8%af%9d%e6%a1%86confirmationdialog/