我正在努力复制 TextField 或 UITextField 的行为,类似于附图中所示的行为。该图片来自Apple Health应用程序的体重输入部分。
我想要实现的目标:
• Display a placeholder.
• Show the clear button (.whileEditing).
• Always display a unit label (e.g., “kg”) next to the value (.always).
但是,当我尝试使用以下代码实现此操作时:
let label = UILabel()
label.text = "kg"
textField?.clearButtonMode = .whileEditing
textField?.rightView = label
textField?.rightViewMode = .always
问题是,当 rightView(单位标签)出现时,清除按钮消失,所以我不能同时拥有两者。我很好奇苹果是否有一种原生方法来实现这种类型的用户体验。
任何见解或解决方案将不胜感激。
我知道十多年前就有人问过类似的问题,但由于当时 SwiftUI 还不存在,所以我再次询问是否有任何新的解决方案可用。
尝试这个简单的方法,使用
selectedId
来确定哪个项目
是要编辑的。调整代码 UI 以满足您的需求。
struct Item: Identifiable {
let id = UUID()
var title: String
var value: Double?
}
struct ContentView: View {
@State private var items = [Item(title: "Height"), Item(title: "Weight"), Item(title: "Blood Type")]
@State private var selectedId: UUID?
var body: some View {
List($items) { $item in
HStack {
Text(item.title).foregroundStyle(.black)
Spacer()
if selectedId == item.id {
TextField(item.title, value: $item.value, format: .number)
.keyboardType(.numberPad)
.frame(width: 88)
Text(" Kg")
} else {
Text(item.value == nil ? "Add" : "\(item.value!)")
.onTapGesture {
selectedId = item.id
}
}
}
.foregroundStyle(.blue)
}
}
}