Natto
Natto

Reputation: 223

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

Upvotes: 1

Views: 2181

Answers (4)

vedhanish
vedhanish

Reputation: 263

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")

Upvotes: 1

Steve B
Steve B

Reputation: 911

You can add a \n in the text string to where you want to create a line break.

Upvotes: 0

iOS Geek
iOS Geek

Reputation: 4855

use below code // HTML Tag Remove Method

extension String{

    func removeHtmlFromString(inPutString: String) -> String{

        return inPutString.replacingOccurrences(of: ".", with: ".\n", options: .regularExpression, range: nil)
    }
}


   let str = "Lorem Ipsum is simply dummy text.Lorem Ipsum has been the industry's standard dummy text ever since the 1500."

  let postDiscription = str!.removeHtmlFromString(inPutString: str!)

Upvotes: 0

KiranMayee Maddi
KiranMayee Maddi

Reputation: 297

Created an outlet for the label and have taken a string which has three sentences separated by ".". The content in the image attached will be this string. Try using replacingOccurences() function as given below.

@IBOutlet weak var trialLabel: UILabel!

var string = "This is a trial text.Let us jump to a new line when the full stop is encountered.Hope it helps."

string = string.replacingOccurrences(of: ".", with: ".\n")
trialLabel.text = string

Check https://developer.apple.com/documentation/foundation/nsstring/1412937-replacingoccurrences for further reference. Happy Coding!!

Upvotes: 4

Related Questions