Vertically align text within a UILabel (Note : Using AutoLayout)

前端 未结 17 2668
忘掉有多难
忘掉有多难 2020-12-23 02:24

I am Copying the same Question asked Before Question. I have tried the solutions given and was not able to solve it since sizetofit was not effective when I

17条回答
  •  执笔经年
    2020-12-23 02:49

    Here's an improvement on the Swift 3 solution by Daniel Galasko (here you can also set the maximum line number without an offset on the top):

    import UIKit
    
    @IBDesignable class TopAlignedLabel: UILabel {
        override func drawText(in rect: CGRect) {
            if let stringText = text {
                let stringTextAsNSString = stringText as NSString
                let labelString = stringTextAsNSString.boundingRect(with: CGSize(width: frame.width, height: .greatestFiniteMagnitude),
                        options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
                super.drawText(in: CGRect(x: 0, y: 0, width: frame.width, height: ceil(labelString.size.height) > frame.height ? frame.height : ceil(labelString.size.height)))
            } else {
                super.drawText(in: rect)
            }
        }
    
        override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
            layer.borderWidth = 1
            layer.borderColor = UIColor.black.cgColor
        }
    }
    

提交回复
热议问题