2017-08-29 64 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

然后,你应该在你的问题(或通过标签)在未来说明。 –