[英]Swift Generic methods for UIView subclasses
I want to create a generic method for all controls like UIButton
, UILabel
, UIView
, UITextView
, to draw underline for every control. 我想为所有控件(如UIButton
, UILabel
, UIView
, UITextView
创建通用方法,以为每个控件绘制下划线。
Is it possible to write such a method for the above classes? 是否可以为上述类编写这样的方法?
Since all elements inherit from UIView
, you can try 由于所有元素都继承自UIView
,因此您可以尝试
extension UIView {
func addUnderline() {
// create underline view add it with addSubview
}
}
you can call it from any element 您可以从任何元素中调用它
UIButton().addUnderline()
UILabel().addUnderline()
and so on 等等
If you really want to use Swift Generics, you could write something like : 如果您真的想使用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.