0
votes

I have added UITextFields programmatically. Here is an example:

addingItemView = UIView(frame: CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight))
let itemNameTextField = UITextField(frame: CGRect(x: 20, y: 40, width: textFieldWidth, height: 20))
itemNameTextField.becomeFirstResponder()
itemNameTextField.placeholder = NSLocalizedString("itemName", comment: "")
itemNameTextField.keyboardType = .default
itemNameTextField.autocorrectionType = .no
itemNameTextField.backgroundColor = UIColor.white
itemNameTextField.layer.cornerRadius = 3
itemNameTextField.borderStyle = .roundedRect
itemNameTextField.clearButtonMode = .whileEditing
itemNameTextField.addTarget(self, action: #selector(assignValueToItemName), for: .editingDidEnd)

addingItemView.addSubview(itemNameTextField)

The issue is: when user is typing more characters than UITextField length, text is not being horizontally scrolled to the left like it happens by default with UITextFields that were added in Storyboard. So user is not able to see what is he typing there.

I have tried to find respective property in UITextField class and in storyboard inspector - no luck. Checked some answers here, for example this, but was not able to find how to scroll text.

Bad example (cursor is not visible, but it's screenshot issue, coz it's blinking):

enter image description here

Good example (TextField added in Storyboard, cursor is not visible, but it's screenshot issue, coz it's blinking):

enter image description here

Kindly advise what am I missing here? Should I implement EditingChanged method and scroll text programmatically? I tried, but did not understand how to do it. I guess moving cursor to position is not the same thing.

3
Have u tried adding it with constraints in code ???Sh_Khan
No I didn't... Will try, thanks.DJ-Glock

3 Answers

3
votes

If textField's height is less than text font size, the textField will not scroll to cursor position.

1
votes

Try this

addingItemView.addSubview(itemNameTextField)
itemNameTextField.translatesAutoresizingMaskIntoConstraints = false
itemNameTextField.widthAnchor.constraint(equalToConstant: textFieldWidth).isActive = true
itemNameTextField.heightAnchor.constraint(equalToConstant: 20).isActive = true
itemNameTextField.leadingAnchor.constraint(equalTo: addingItemView .leadingAnchor, constant: 20).isActive = true
itemNameTextField.topAnchor.constraint(equalTo: addingItemView .topAnchor, constant:40).isActive = true
0
votes

My particular issue was resolved by increasing height size from 20 to 25. Most probably it happened because iOS was not able to adjust text because of font size and textfield height.

let itemNameTextField = UITextField(frame: CGRect(x: 20, y: 40, width: textFieldWidth, height: 25))