简体   繁体   中英

Assign text to a line of a multi-line UILabel

UILabel's text is assigned as a whole. If there is a multi-line label is there a way to assign a string of text to a specific line of that label.

So that instead of doing myLabel.text = "A very long line...." can I do something like myLabel.text.line[0] /*(or [1] or whatever)*/ = "One line from my whole string" ?

You can add line breaks in your string with "\\n"

myLabel.text = "A \n very long \n line"

Note: Set the label's number of lines to 0, to allow any any number of lines.

myLabel.numberOfLines = 0

You could create an array of lines and then assign the text to the lines like this:

var lines = [String]()
lines.append("Line number 1")
lines.append("Line number n")

and then you could do something like this:

func setLabelTextForLines(lines:[String]){
    var text = ""
    for line in lines {
        text += line
        text += "\n"
    }

    myLabel.numberOfLines = 0
    myLabel.text = text
}

So you could have an array called lines and edit it and then call the function to reassign the text:

setLabelTextForLines(lines)
lines[0] = "Changed the first line"
setLabelTextForLines(lines)

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