首页 > 学院 > 开发设计 > 正文

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

2019-11-06 09:42:36
字体:
来源:转载
供稿:网友

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

import UIKitenum 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)    }}


上一篇:ViewPager异常总结

下一篇:沉浸式模式

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表