当我单击键盘上的返回按钮时,该应用程序冻结,并且再也没有响应。我正在使用返回public static<T> Stream<T> of(T... values)
的{{1}},因为我无法使用SwiftUI在文本上创建轮廓。我正在Xcode beta 5和iPhone XR模拟器上运行它。
UIViewRepresentable
我希望单击返回按钮时,应用程序会关闭键盘,但应用程序会冻结。
答案 0 :(得分:0)
该答案的积分转到https://github.com/valvoline/SATextField/blob/master/SATextField/ContentView.swift。没有以上消息来源,答案就不会在这里。
专业没有改变。
struct CustomTextField: View {
@State var text: String
@State var pos: CGPoint
var body: some View {
StrokeTextLabel(text: $text, changeHandler: { newString in
self.text = newString
}, onCommitHandler: {
print("commitHandler")
})
.position(pos)
.gesture(dragGesture)
}
var dragGesture : some Gesture {
DragGesture()
.onChanged { value in
self.pos = value.location
print(self.pos)
}
}
}
添加了UITextField和UITextFieldDelegate以使用其功能
class WrappableTextField: UITextField, UITextFieldDelegate {
var textFieldChangedHandler: ((String)->Void)?
var onCommitHandler: (()->Void)?
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let currentValue = textField.text as NSString? {
let proposedValue = currentValue.replacingCharacters(in: range, with: string)
textFieldChangedHandler?(proposedValue as String)
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
onCommitHandler?()
}
}
使用委托作为对象并添加属性。还使字符串成为Binding
struct StrokeTextLabel: UIViewRepresentable {
private let tmpView = WrappableTextField()
@Binding var text: String
//var exposed to SwiftUI object init
var changeHandler:((String)->Void)?
var onCommitHandler:(()->Void)?
func makeUIView(context: Context) -> UITextField {
tmpView.delegate = tmpView
tmpView.onCommitHandler = onCommitHandler
tmpView.textFieldChangedHandler = changeHandler
let attributedStringParagraphStyle = NSMutableParagraphStyle()
attributedStringParagraphStyle.alignment = NSTextAlignment.center
let attributedString = NSAttributedString(
string: text,
attributes:[
NSAttributedString.Key.strokeColor : UIColor.white,
NSAttributedString.Key.foregroundColor : UIColor.black,
NSAttributedString.Key.strokeWidth : -4.0,
NSAttributedString.Key.font: UIFont(name: "impact", size: 50.0)!
]
)
tmpView.attributedText = attributedString
tmpView.autocorrectionType = .no
tmpView.keyboardType = .default
return tmpView
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
uiView.setContentHuggingPriority(.defaultLow, for: .horizontal)
}
}