基于字符串的动态 UILabel



我有一个UILabel.UILabel中的文本如下所示:

Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Website - example.com
YouTube - youtube.com/example
Twitter - twitter.com/example
Instagram - twitter.com/example

所以这个文本是动态的。我从 API 获取字符串,API 包含一个类似于上面的字符串。第一段更改。它可以是多个段落或任何内容。但是带有网站链接的文本保持不变。

所以基本上,我希望标签只显示字符串的第一部分。然后,每当用户按下按钮时,它都会显示整个字符串。我无法设置numberOfLines,因为字符串的第一部分发生了变化。有没有办法告诉标签只显示文本

Website - example.com
YouTube - youtube.com/example
Twitter - twitter.com/example
Instagram - twitter.com/example

然后每当按下按钮时,显示整个字符串?

我正在使用 Swift 4。

如果它的格式相同,并且您知道将第一个字符串与其他字符串分开的元素,则可以在字符串上使用 split 函数将原始 str 拆分为子字符串。

class ViewController: UIViewController 
{
@IBOutlet weak var myLabel: UILabel!
let strFromApi = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. nWebsite - example.com nYouTube - youtube.com/example nTwitter - twitter.com/example nInstagram - twitter.com/example"
override func viewDidLoad()
{
super.viewDidLoad()
self.myLabel.text = getFirstSection(of: strFromApi)
}
func getFirstSection(of str: String) -> String
{
if let newStr = str.split(separator: "n").first
{
return String(newStr)
}
return str
}
@IBAction func seeMoreAction(_ sender: UIButton)
{
self.myLabel.text = strFromApi
}
}

您可以将标签的文本拆分为两部分:从 API 获取的labelContent,以及要添加到标签的固定字符串labelFooter。然后,将属性观察器放在它们上以更新UILabel

class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
/// The actual text that you get from the API
var labelContent = "" {
didSet {
label.text = labelContent + (isExpanded ? labelFooter : "")
}
}
/// The fixed footer string
let labelFooter = """

Website - example.com
YouTube - youtube.com/example
Twitter - twitter.com/example
Instagram - twitter.com/example
"""
/// Whether or not the label shows the footer
var isExpanded = false {
didSet {
// A trick to trigger `didSet` on `labelContent`
labelContent = { labelContent }()
}
}
override func viewDidLoad() {
// Get this from the API
labelContent = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
// This is a trick to trigger to `didSet` observer on `isExpanded`
isExpanded = { isExpanded }()
}
/// The action to show/hide the footer
@IBAction func toggleExpand(_ sender: Any) {
isExpanded = !isExpanded
}
}

最新更新