Simon Z. Simon Z. - 3 months ago 10
iOS Question

Swift iOS - Bottom Border on TextField initial wrong width

I implement a solution to put a bottom border to a textfield which works good but i have following Problem. If i start the app on bigger sizes (iPad mini, iPad Pro) or landscape (iPhone6, 6s) the line under the textfield is not correct stretched.

I have create a extension for the textfields:

extension UITextField {
/**
Customize the UITextField for App

- parameter isPasswordField: Boolean to check if this field is a password field

- author: Simon Zwicker <simon.zwicker@gmail.com>
*/
func customize(isPasswordField: Bool) {
let bottomLine = UIView()
bottomLine.frame = CGRect(x: 0.0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1.0)
bottomLine.backgroundColor = UIColor.grayColor()
self.addSubview(bottomLine)

self.tintColor = UIColor.grayColor()

if isPasswordField {
self.textColor = UIColor.blueColor()
}
}


I call the
customize()
function on the textfields in
viewWillLayoutSubviews()


Did i make somewhere a mistake? After i put device in portrait and back to landscape it works.

The size of the textfield is initial correct but the self.frame.size.width in the customize function is initial too small. Do you know what happened maybe?

Answer

I was able to replicate your issue, and it seems like at the moment of calling viewWillLayoutSubviews the text field did not have the width that's shown on the screen in the end (or constraints weren't applied).

Calling customize in viewDidLayoutSubviews scaled the line properly. I am not sure if you are happy with this solution.

Comments