在 SwiftUI 中,可以使用 UIViewRepresentable
将 UITextView
包装为 SwiftUI 控件,并实现 UIWebViewDelegate
来禁止长按放大功能。代码示例如下:
struct TextView: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isScrollEnabled = true
textView.isEditable = true
textView.isUserInteractionEnabled = true
textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.autocapitalizationType = .sentences
textView.keyboardType = .default
textView.returnKeyType = .default
textView.enablesReturnKeyAutomatically = true
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: TextView
init(_ parent: TextView) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
self.parent.text = textView.text
}
// 禁止长按放大功能
func textViewDidChangeSelection(_ textView: UITextView) {
textView.selectedTextRange = nil
}
}
}
在 Coordinator
中实现 textViewDidChangeSelection
方法,将 textView.selectedTextRange
设置为 nil,即可禁止长按放大功能。