Noodledew
Noodledew

Reputation: 519

Have autosizing text in a viewcontroller

Can someone tell my why this code does not autosize the text in the descLabel? I tried to set the numberOfLines to 0 and I set a lineBreakMode but this pretty much does nothing to solve my problem. Is this approach not possible in a ViewController or do I do something completely wrong?

class SingleEventViewController: UIViewController {

var thisEvent: Event
var eventDescription: String?

let descLabel: UILabel = {
    let label = UILabel()
    label.font = UIFont.systemFont(ofSize: 16)
    label.text = "Beschreibung"
    label.textColor = .black
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    return label
}()  

let participateButton: UIButton = {
    let button = UIButton()
    button.backgroundColor = CalendarSettings.Colors.buttonBG
    button.setTitle("Teilnehmen", for: .normal)
    button.setTitleColor(CalendarSettings.Colors.darkRed, for: .normal)
    return button
}()

//MARK: - Init & View Loading
init(event: Event) {
    thisEvent = event
    super.init(nibName: nil, bundle: nil)
    setupDefaultValues()
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    applyDefaultValues()
    setupViews()
    confBounds()
}

//MARK: - Setup
func setupDefaultValues() {
    eventDescription = thisEvent.eventDescription
}

func applyDefaultValues() {
    descLabel.text = eventDescription
}

func setupViews() {
    view.addSubview(descLabel)
    view.addSubview(participateButton)

    let tabbarHeight = self.tabBarController?.tabBar.frame.height ?? 0
    descLabel.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    participateButton.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: tabbarHeight, paddingRight: 0, width: 0, height: 50) 
}

Upvotes: 0

Views: 62

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

To make it autoresize you must give it a left/leading and right/trailing constraints , or a fixed width

descLabel.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, bottom: nil, rightview.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

Upvotes: 1

GetSwifty
GetSwifty

Reputation: 13

If it is the font size you are trying to change so that it fits in the label then try adjustFontSizeToWidth, but if it is the label you wish to resize try sizeToFit().

Upvotes: 0

Related Questions