2017-08-29 59 views

回答

1

您可以使用NSAttributedStringNSKernAttributeName作爲字母間距。我創建了供您使用簡單的子類:

class StretchingLabel: UILabel { 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     sharedInit() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     sharedInit() 
    } 

    private func sharedInit() { 
     self.lineBreakMode = .byClipping 
     self.textAlignment = .center 
    } 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     realignText() 
    } 

    private var scale: CGFloat { return UIScreen.main.scale } 

    override var text: String? { 
     didSet { 
      realignText() 
     } 
    } 

    private func realignText() { 
     guard let text = text else { return } 

     let textWidth = ceil((text as NSString).boundingRect(with: self.frame.size, options: [], attributes: [NSFontAttributeName: self.font], context: nil).width * scale)/scale 
     let availableWidth = self.frame.width - textWidth 
     let interLetterSpacing = availableWidth/CGFloat(text.characters.count - 1) 

     let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: self.font, NSKernAttributeName: interLetterSpacing]) 
     self.attributedText = attributedText 
    } 

} 
+0

嗯,我使用對象-C進行開發,但是謝謝你看我的問題,我看了你的答案是有用的我issue.It是一個很好的理念。 –

+0

然後,你應該在你的問題(或通過標籤)在未來說明。 –