'Keyboard dismisses on every character typed in text input in Swift
I have one textField.
private var verseTitle: UITextField = {
let tf = UITextField()
tf.placeholder = "TITLE"
tf.font = UIFont(suite16: .tBlackItalic, size: 18)
tf.textColor = .black.withAlphaComponent(0.5)
tf.returnKeyType = .done
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
In viewDidLoad method, I have assigned self as delegate.
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
verseTitle.delegate = self
}
In viewDidLayout method, I'm using stack view to add textField to the view.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Title
let titleStack = UIStackView()
titleStack.axis = .horizontal
titleStack.alignment = .center
titleStack.distribution = .equalSpacing
titleStack.spacing = 8
titleStack.addArrangedSubview(verseTitle)
titleStack.addArrangedSubview(floorView)
titleStack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(titleStack)
NSLayoutConstraint.activate([
floorView.heightAnchor.constraint(equalToConstant: 13),
floorView.widthAnchor.constraint(equalToConstant: 13),
titleStack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
titleStack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
])
}
Now, the problem I'm facing is, that when I start typing in the textField, the keyboard gets dismissed only after I type one letter. I'm not sure why this is happening. I have to tap on the field after entering each letter. For some reason, the focus is taken away from the field after each letter is entered (unless I tap on a suggested autocorrect - the whole string is correctly added to the string at once)
Solution 1:[1]
I was able to solve the problem successfully with this bit of code:
items = []
def render(json_data, v=""):
if isinstance(json_data, dict):
items.append(f"<ul>")
for k2, v2 in json_data.items():
render(k2 ,v2) # <---If we have a dict, apply function again
items.append(f"</ul>")
elif isinstance(v, dict):
items.append(f"<li>{json_data}: <ul>")
for k2, v2 in v.items():
render(k2 ,v2) # <---If we have a dict, apply function again
items.append("</ul></li>")
elif isinstance(v, list):
items.append(f"<li>{json_data}:<ul>")
for i in v:
if isinstance(i, str):
items.append(f"<li>{i}</li>")
elif isinstance(i, dict):
render(i, v)
items.append("</ul></li>")
else:
items.append(f"<li>{json_data}: {v}</li>")
render(data)
html_str = "".join(items)
html_str
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kyle |
