myUILabel是一個能夠根據文字內容計算出文字在標籤上的垂直居中功能的插件。git
地址:github
http://blog.csdn.net/yexiaozi_007/article/details/8636522swift
沒有作成一個項目,只是兩個文件。導入項目,橋接以後,就可正常使用。ide
拖入組件到Storyboard中,在Identity Inspector中Custom Class的Class設置爲myUILabel
。如哪裏設置這個UILabel的垂直竟然中呢?在代碼中去設置相應Label的垂直對齊方式便可。ui
@IBOutlet weak var textLbel: myUILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textLbel.verticalAlignment = VerticalAlignmentTop }
三種對齊方式分別是:.net
上:VerticalAlignmentTop插件
中:VerticalAlignmentMiddle,code
下:VerticalAlignmentBottom,orm
發現一個Swift版的:blog
參考這段代碼,我做了一些調整,這段代碼能夠放到Swift項目中,能夠拖入給件創建關聯,指定Class爲myUILabel後,即能正常使用,也能夠直接在以代碼的方式建立一個myUILabel也可。
// // myUILabel.swift // myUILabelDemo // // Created by wyatt on 15/11/29. // Copyright © 2015年 Wanqing Wang. All rights reserved. // import UIKit enum VerticalAlignment { case Top case Middle case Bottom } class myUILabel: UILabel { var verticalAlignment: VerticalAlignment = .Bottom { willSet { self.setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) self.verticalAlignment = VerticalAlignment.Middle } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var textRect = super.textRectForBounds(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: fallthrough default: textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2 } return textRect } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { let actualRect = self.textRectForBounds(rect, limitedToNumberOfLines: self.numberOfLines) super.drawTextInRect(actualRect) } }
關於required init?(coder aDecoder: NSCoder)
這個初始化方法是必須定義的,Xcode提供的默認的代碼是這樣的:
required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
但以組件關聯的方式就會報錯,而如以代碼的方式來建立myUILabel的話,倒是能正常工做的,固然這不是我所須要的,我須要的是能夠直接拖放的方式進行操做便可的。
具體的什麼緣由Xcode選用這種方式來初始化,我暫時沒能想明白。而這個初始化方式是怎麼回事,我也還不清楚。
若是你知道怎麼回事,還麻煩告訴一下我。