常用于要求 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) }}
新闻热点
疑难解答