swift 自定义一个可设置 text 的垂直位置的 Label

前端之家收集整理的这篇文章主要介绍了swift 自定义一个可设置 text 的垂直位置的 Label前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

常用于要求 label 文字上部与图片上部对齐的场景

import UIKit

enum VerticalAlignment
{
    case VerticalAlignmentTop//default
    case VerticalAlignmentMiddle
    case VerticalAlignmentBottom
}


class VerticalLabel: UILabel
{
    var verticalAlignment: VerticalAlignment = .VerticalAlignmentTop {
        didSet {
            self.setNeedsDisplay()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.verticalAlignment = VerticalAlignment.VerticalAlignmentTop
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    
    override func textRect(forBounds bounds: CGRect,limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        var superRect:CGRect = super.textRect(forBounds: bounds,limitedToNumberOfLines: numberOfLines)
        switch self.verticalAlignment {
        case VerticalAlignment.VerticalAlignmentTop:
            superRect.origin.y = bounds.origin.y
        case VerticalAlignment.VerticalAlignmentBottom:
            superRect.origin.y = bounds.origin.y + bounds.size.height  - superRect.size.height
        case VerticalAlignment.VerticalAlignmentMiddle:
            superRect.origin.y = bounds.origin.y + (bounds.size.height - superRect.size.height) / 2
        }
        return superRect
    }
    override func drawText(in rect: CGRect) {
        let rect:CGRect = self.textRect(forBounds: rect,limitedToNumberOfLines: self.numberOfLines)
        super.drawText(in: rect)
    }

}
原文链接:https://www.f2er.com/swift/322083.html

猜你在找的Swift相关文章