自定义UI控件:继承UIlabel,使label中的文字居上,居中,居下

一般来说,在ios里面label中的文字垂直方向上是默认居中的,如果想要设置居上或者居下,在xib文件里面不能设置,只能自定义一个UI控件。
label文字的水平位置,可以在xib文件中直接设置。

import UIKit

/// カスタムUIコントロール
class TextPositionLabel: UILabel {
    
    var verticalAlignment : VerticalAlignment?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.verticalAlignment = VerticalAlignment.middle
        
    }
    
	override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
		var textRect: CGRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
		switch self.verticalAlignment {
			case .top?:
            	textRect.origin.y = bounds.origin.y
        	case .bottom?:
            	textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height
        	case .middle?:
            	textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0
        	default:
        		// デフォルトが居中です
            	textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0
        }
        return textRect
    }
    
	override func draw(_ rect: CGRect) {
		let rect : CGRect = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
        super.drawText(in: rect)
    }
    
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
    
}


/// labelの文字列の位置タイプ
public enum VerticalAlignment {
	// 居上
    case top
    // 居中
    case middle
    // 居下
    case bottom
}
发布了10 篇原创文章 · 获赞 0 · 访问量 312

猜你喜欢

转载自blog.csdn.net/weixin_42163902/article/details/104081279