自定義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 · 訪問量 4678
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章