Search code examples
iosswiftuilabeluitextview

Swift - UITextView does not display text


My UITextView does not display its text and I have no idea why.

let linkLabel: UITextView = {
    let v = UITextView()
    v.backgroundColor = .clear
    v.text = "Link"
    v.textColor = .lightGray
    v.font = UIFont(name: "AvenirNext", size: 18)
    v.font = v.font?.withSize(18)
    v.textAlignment = .right
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

It was a UILabel before and working perfectly fine. But I need it to be a UITextView. However if I change it to UITextView like in the code the text is not getting displayed.

Any idea why that happens?


Solution

  • Your UITextView frame is equal to CGRect.zero and unlike a UILabel, a UITextView does not have an intrinsic frame. That's why you don't see it.


    Solution

    1. Use init(frame: CGRect)

    UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
    
    1. Set a frame property later

    let v = UITextView()
    v.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
    

    Important:

    The linkLabel have to be added to the view via InterfaceBuilder or in code with a method view.addSubview of the UIView object

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(linkLabel)
    }
    

    Debug techniques:

    • Debug View Hierarchy

    Click the Debug View Hierarchy button in the bar at the top of the debug area to inspect a 3D rendering of the view hierarchy of your paused app

    enter image description here