iOS 之 UILabel 文本在其 frame 内垂直顶部、居中、底部对齐


import UIKit

// UILabel 文本在其 frame 内垂直顶部、居中、底部对齐
enum UUTextVerticalAlignment {
    case top
    case middle
    case bottom
}

class UULabel: UILabel {
    var verticalAlignment: UUTextVerticalAlignment = .middle {
        didSet {
            setNeedsDisplay()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        var textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        switch verticalAlignment {
        case .top:
            textRect.origin.y = bounds.origin.y
        case .middle:
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0
        case .bottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height
            
        }
        return textRect
    }

    override func drawText(in rect: CGRect) {
        let actualRect = textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
        super.drawText(in: actualRect)
    }
}


你可能感兴趣的:(iOS 之 UILabel 文本在其 frame 内垂直顶部、居中、底部对齐)