UILabel线间距

Rob*_*ert 5 xcode objective-c uilabel ios swift

我想设置的行间距在UILabel由Mike斯拉斯基指定位置.它适用于我从Storyboard指定的文本.当我尝试设置UILabel.text代码时,它将恢复为默认行间距.有人可以帮我理解如何:

  1. 使其不会恢复为默认值,并使用我在Storyboard上指定的设置或

  2. 在代码中设置值.

我已经看过很多关于使用NSAttribute和的例子NSParagraph,但由于现在可以设置在故事板中,我希望它们可能是一个更简单的答案.非常感谢您的帮助!

我设置了"高度倍数",如上面的链接所示,我唯一的代码如下:

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.
    }

}
Run Code Online (Sandbox Code Playgroud)

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

mat*_*att 11

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

但是,如果你随后出现并text在代码中设置标签,就像你正在做的那样,你会抛弃它attributedText 所有的属性.这就是为什么,正如你正确地说,事情会恢复到标签的默认外观.

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

所以例如(我已经调用了我的标签lab- 你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
Run Code Online (Sandbox Code Playgroud)