Emre Önder
Emre Önder

Reputation: 2537

Wordwrap label in Swift

I searched for this problem but the solutions i found didn't work for me. I have a textfield. When user writes something to textfield, it writes it to the label. This label is on an imageview, when label reaches the imageview limits. I want that label wordwrap and go to second line. Now it is like this but doesn't work.

    @IBAction func textchanged(_ sender: UITextField) { 
    if(mylabel.frame.minX < imageview.frame.minX && mylabel.frame.maxX > imageview.frame.maxX)
    {
    mylabel.frame = CGRect(x: mylabel.frame.origin.x, y: mylabel.frame.origin.y, width: mylabel.frame.width, height: mylabel.frame.height * 2 )
    mylabel.numberOfLines = 2
    mylabel.lineBreakMode = NSLineBreakMode.byWordWrapping
    mylabel.sizeToFit()
    }
    mylabel.numberOfLines = lines
    mylabel.text = textfield.text
    mylabel.sizeToFit()
}

screenshot

Upvotes: 3

Views: 15090

Answers (2)

Krishna Datt Shukla
Krishna Datt Shukla

Reputation: 997

Remove height constraint from label in Xib (If you have set constraint for height)

and Use this

label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
label.text = textfield.text

Upvotes: 2

Alex Thomas
Alex Thomas

Reputation: 38

Try updating label in the delegate function

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

Also see that uitextfield delegate is properly set

Upvotes: 0

Related Questions