swiftui - Editable Text() [ Text() that can be TextField() on double tap]
问题描述
Some time ago I had a problem with making UI logic of view that can be Label and EditBox both:
I mean Text()
-> doubleClick action -> display TextEdit()
-> fill it with new text -> Enter key press -> text changes saved and displayed in Text()
solution is in answer below
解决方案
import SwiftUI
@available(macOS 10.15, *)
public struct EditableLabel: View {
@Binding var text: String
@State private var newValue: String = ""
@State var editProcessGoing = false { didSet{ newValue = text } }
let onEditEnd: () -> Void
public init(_ txt: Binding<String>, onEditEnd: @escaping () -> Void) {
_text = txt
self.onEditEnd = onEditEnd
}
@ViewBuilder
public var body: some View {
ZStack {
// Text variation of View
Text(text)
.opacity(editProcessGoing ? 0 : 1)
// TextField for edit mode of View
TextField("", text: $newValue,
onEditingChanged: { _ in },
onCommit: { text = newValue; editProcessGoing = false; onEditEnd() } )
.opacity(editProcessGoing ? 1 : 0)
}
// Enable EditMode on double tap
.onTapGesture(count: 2, perform: { editProcessGoing = true } )
// Exit from EditMode on Esc key press
.onExitCommand(perform: { editProcessGoing = false; newValue = text })
}
}
sample of usage:
EditableLabel($name, onEditEnd: { print("New name is *\(name)* ") } )
推荐阅读
- ruby-on-rails - Rails 5:(没有路线匹配[HEAD]“资产”
- prolog - 如何在“SWISH”“Prolog”中添加空格?
- java - Keycloak社交登录休息api
- string - 在单引号字符串中使用双引号会更改转义行为
- superset - 网页中的 Apache 超集仪表板
- python - 删除重复行但保留某些值 Pandas
- c - 将 double 转换为 int 而不四舍五入
- sql - 在bigquery中根据条件合并记录
- docker - 如何制作安全的 nginx-proxy 以在单个服务器中指向不同的路径?
- .net-core - VS for Mac 2017 使用 .NET Core SDK 而不是 Mono 构建