Search code examples
swiftuitextfieldboundssize-classes

swift - UITextField self.bounds inconsistency when no size classes selected


I've got a custom UITextField that adds a sublayer to a UITextField for a colour gradient. In my view controller I have text fields that are intended to go the full width of the screen.

import UIKit
import Foundation

class CustomTextField: UITextField {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        /* gradient color and location code */
        self.layer.insertSublayer(gradientLayer, atIndex: 0)
    }
}

I've also disabled size classes.

My problem is that when running on a simulator bigger than 3.5", the gradient doesn't go right across the text field. The error seems to be the self.bounds not evaluating the bigger width.

Any suggestion that don't require enabling size classes?


Solution

  • View bounds are calculated during UIView.layoutSubviews(). You need to override this method:

    import UIKit
    
    class CustomTextField: UITextField {
        private let gradientLayer = CAGradientLayer()
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            layer.insertSublayer(gradientLayer, atIndex: 0)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            gradientLayer.frame = bounds
        }
    }