找到特定字符后,为UILabel文本插入换行符

时间:2018-03-27 18:26:23

标签: ios swift string text uilabel

我有一个UILabel,每次单击按钮时都会动态更新,数据将从firebase获取并显示在uilabel上。我能够显示如下所示的文本。我希望在文本中遇到特定分隔符(例如'。' PERIOD)时插入换行符。我已经研究了许多关于UIlabel换行符的解决方案,但无法找到我正在寻找的解决方案,每个解决方案都处理我们在故事板本身提供的静态文本。任何帮助将不胜感激。谢谢。 enter image description here

UILabel text content

4 个答案:

答案 0 :(得分:3)

为标签创建了一个出口,并取了一个字符串,其中有三个句子用"。"分隔。附加图像中的内容将是此字符串。尝试使用replacementOccurences()函数,如下所示。

@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

检查https://developer.apple.com/documentation/foundation/nsstring/1412937-replacingoccurrences以获取进一步的参考。快乐编码!!

答案 1 :(得分:1)

您可以使用UILabel的属性text属性来实现此目的。尝试使用html换行符查找并替换该字符,然后将此文本分配给UILabel属性文本。

您可以通过

替换字符串

let str ="这是要用新字符串替换的字符串" let replacementStr = str.replacingOccurrences(of:" string",with:" str")

答案 2 :(得分:0)

使用下面的代码 // HTML标记删除方法

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

答案 3 :(得分:0)

您可以在文本字符串中添加\ n到要创建换行符的位置。