[英]Swift Generic methods for UIView subclasses
我想為所有控件(如UIButton
, UILabel
, UIView
, UITextView
創建通用方法,以為每個控件繪制下划線。
是否可以為上述類編寫這樣的方法?
由於所有元素都繼承自UIView
,因此您可以嘗試
extension UIView {
func addUnderline() {
// create underline view add it with addSubview
}
}
您可以從任何元素中調用它
UIButton().addUnderline()
UILabel().addUnderline()
等等
如果您真的想使用Swift泛型,則可以編寫如下內容:
func addUnderline<V>(inView view: V, withHeight height: CGFloat, andColor color: UIColor) where V: UIView {
let underlineHeight: CGFloat = height
let underlineView = UIView(frame: CGRect(x: 0, y: view.frame.height - underlineHeight, width: view.frame.width, height: underlineHeight))
underlineView.backgroundColor = color
view.addSubview(underlineView)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.