Search code examples
iosswiftstringtextuilabel

Insert line break for UILabel text when a specific character is found


I have a UILabel that dynamically gets updated every time I click a button, the data will be fetched from firebase and displayed on the uilabel.I am able to display the text as shown below. I would like to insert a line break when a specific delimiter(say '.' PERIOD) is encountered in the text. I have looked into many solutions about UIlabel line break but couldn't find one what exactly I am looking for, every solution deals with static text that we provide in the storyboard itself. Any help will be appreciated. Thank you. enter image description here)

UILabel text content


Solution

  • You can achieve this with the attributed text property of UILabel. Try to find and replace the character with html line break and then assign this text to the UILabel attributed text.

    You can replace string by

    let str = "This is the string to be replaced by a new string"
    let replacedStr = str.replacingOccurrences(of: "string", with: "str")