简体   繁体   中英

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?

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

在此处输入图片说明

You can use sizeToFit() and isScrollEnabled to false like below:

let linkLabel: UITextView = {
        let v = UITextView()
        v.backgroundColor = .red
        v.text = "Link"
        v.textColor = .lightGray
        v.font = UIFont(name: "AvenirNext", size: 18)
        v.font = v.font?.withSize(18)
        v.textAlignment = .right
        v.sizeToFit()
        v.isScrollEnabled = false
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
// And set the frame whereever you want 
linkLabel.frame.origin = CGPoint(x: 100, y: 100)
self.view.addSubview(linkLabel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM