mah*_*han 6 text-editor ios swiftui
我有一个文本编辑器,我不允许用户在其中添加换行符 (\n) 。也就是说,当用户Enter时,我关闭键盘。我使用以下代码来关闭键盘并阻止用户添加新行。
Enter时键盘会消失,但不会阻止用户添加新行。当您输入.
extension View {
func dismissKeyboard(){
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
keyWindow?.endEditing(true)
}
}
struct Editor: View {
@Binding var text: String
var onEditingEnded: () -> ()
var body: some View {
ZStack(alignment: .leading) {
TextEditor(text: $text)
.onChange(of: text) { value in
if value.last == "\n" {
self.dismissKeyboard()
self.onEditingEnded()
}
}
}
.padding(8)
.font(.body)
}
}
Run Code Online (Sandbox Code Playgroud)
如何防止用户添加新行?
您可以使用UITextView
具有shouldChangeTextIn range
委托功能的...
或者,虽然不是我所说的理想状态,但这可能对你有用:
TextEditor(text: $text)
.onChange(of: text) { value in
if value.last == "\n" {
text = String(value.dropLast())
self.dismissKeyboard()
self.onEditingEnded()
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您仅检查字符串中的最后一个字符,因此这不会处理用户在现有文本中间添加换行符的情况。
所以,你可以尝试:
TextEditor(text: $text)
.onChange(of: text) { value in
if value.contains("\n") {
text = value.replacingOccurrences(of: "\n", with: "")
self.dismissKeyboard()
self.onEditingEnded()
}
}
Run Code Online (Sandbox Code Playgroud)
与 DonMag 的答案类似,您也可以使用Binding()
代替来.onChange()
避免之后更改值并在设置之前采取行动:
TextEditor(text: Binding(
get: {
return text
},
set: { value in
var newValue = value
if value.contains("\n") {
newValue = value.replacingOccurrences(of: "\n", with: "")
self.dismissKeyboard()
self.onEditingEnded()
}
text = newValue
}
))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2682 次 |
最近记录: |