UILabel线间距

时间:2015-05-22 00:15:14

标签: ios objective-c swift xcode uilabel

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

  1. 使其无法恢复为默认值,并使用我在故事板上指定的设置或

  2. 在代码中设置值。

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

    我设置了“Height Multiple”,如上面的链接所示,我唯一的代码如下:

    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行,它会正确显示,否则会重新设置为默认行间距(或高度倍数)。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

UILabel

@property(nonatomic, copy) NSAttributedString *attributedText 自iOS 6.0起,

默认情况下,此属性为零。为此属性分配新值也会使用相同的字符串数据替换text属性的值,尽管没有任何格式信息。此外,指定新值可更新font,textColor和其他与样式相关的属性中的值,以便它们反映从属性字符串中的位置0开始的样式信息。

如果再次设置textView.text = "Some example text",则会丢失属性。如果你确定自己在做什么,你应该只选择其中一个而不是在它们之间切换

答案 2 :(得分:1)

这是@matt在Obj的回答。 C:

  NSMutableAttributedString *mas = [self.lab.attributedText mutableCopy];
  [mas replaceCharactersInRange:NSMakeRange(0, [mas.string length]) 
    withString:@"Little poltergeists make up the principle form of material manifestation"]; 
  self.lab.attributedText = mas;

希望这有助于某人!

答案 3 :(得分:1)

Swift 3 只需复制&执行此代码以查看结果

let label = UILabel()
let stringValue = "UILabel\nLine\nSpacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
相关问题