gpt4 book ai didi

ios - UILabel 行间距

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:44 26 4
gpt4 key购买 nike

我正在尝试按照 Mike Slutsky 的规定在 UILabel 中设置行间距 here .它适用于我从 Storyboard 中指定的文本。当我尝试在代码中设置 UILabel.text 时,它会恢复为默认行间距。有人可以帮助我了解如何:

  1. 避免恢复为默认设置,并使用我在 Storyboard 或

  2. 上指定的设置
  3. 在代码中设置值。

我看过很多关于使用 NSAttributeNSParagraph 的例子,但由于现在可以在 Storyboard 中设置,我希望它们可能更直截了当的答案。非常感谢您的帮助!

我按照上面的链接设置了“高度倍数”,我唯一的代码如下:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textView: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

textView.text = "Some example text"
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

如果我删除 textView.text 行,它会正确显示,否则会设置回默认行间距(或高度倍数)。

最佳答案

这是正在发生的事情。您可以使用自定义行间距在 Storyboard 中进行设置。这意味着,即使您可能不知道,您已经在 Storyboard中设置了标签的 attributedText

但是,如果您随后开始在代码中设置标签的 text,正如您正在做的那样,您将丢弃 attributedText ,因此所有属性 它有。这就是为什么,正如您所说的那样,事情会恢复到标签的默认外观。

解决方案是:不是设置标签的text,而是设置它的attributedText。特别是,获取标签的现有 attributedText;将其分配到 NSMutableAttributedString 中,以便您可以更改它;在保留属性的同时替换其字符串;并将其分配回标签的 attributedText

例如(我将我的标签命名为 lab - 你的 textView 是一个糟糕的选择,因为 TextView 是完全不同的动物):

let text = self.lab.attributedText
let mas = NSMutableAttributedString(attributedString:text)
mas.replaceCharactersInRange(NSMakeRange(0, count(mas.string.utf16)),
withString: "Little poltergeists make up the principle form of material manifestation")
self.lab.attributedText = mas

关于ios - UILabel 行间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com