2015-05-22 139 views
4

我試圖按照Mike Slutsky here指定的UILabel設置行間距。它對於我從Storyboard指定的文本正常工作。當我嘗試在代碼中設置UILabel.text時,它將恢復爲默認行間距。有人可以幫助我瞭解如何之一:UILabel行間距

  1. 保持它恢復爲默認值,並使用我的故事板指定或

  2. 在代碼中設置值的設置。

我已經看到了很多的例子使用周圍和NSAttributeNSParagraph,但因爲它是現在可以在故事板來設置,我希望自己可以是一個更明確的答案。非常感謝您的幫助!

我設置如圖所示在上面的鏈接,和我唯一的代碼如下的「高度多」:

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線,它會顯示正確的,否則它的設置回到默認行間距(或高度倍數)。

+0

顯示_your_代碼。 – matt

+0

沒有很多代碼可以顯示,但是我已經添加了它。感謝您的建議。 – Robert

+0

實際上非常有幫助!這給了我一個更好的想法是什麼問題。我想我可以根據這個來回答。 – matt

回答

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 
+0

在描述中增加了一些實際代碼。 – matt

+0

這是完全意義上的。感謝您的回覆和代碼!我得到的錯誤** utf16Count'不可用:取一個UTF-16視圖的計數,而不是計數(str.utf16)**,但我正在研究一個解決方案。再次感謝 – Robert

+0

你說得對,我在舊版本的Xcode下測試過。對於那個很抱歉。 – matt

1

的UILabel有

@property(nonatomic, copy) NSAttributedString *attributedText 以來的iOS 6.0 ,

該屬性默認爲零。爲該屬性分配一個新值也會將文本屬性的值替換爲相同的字符串數據,儘管沒有任何格式信息。另外,分配一個新的值會更新字體,textColor和其他樣式相關屬性中的值,以便它們反映屬性字符串中從位置0開始的樣式信息。

如果您再次設置了textView.text = "Some example text",則會丟失屬性。你應該只挑他們其中的一個,而不是在它們之間切換,如果你確定你在做什麼

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; 

希望這可以幫助別人!

0

斯威夫特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