【问题标题】:Swift Generic methods for UIView subclassesUIView 子类的 Swift 通用方法
【发布时间】:2018-09-13 10:51:28
【问题描述】:

我想为UIButtonUILabelUIViewUITextView 等所有控件创建一个通用方法,以便为每个控件绘制下划线。

上面的类可以写这样的方法吗?

【问题讨论】:

    标签: ios swift generics uicontrol


    【解决方案1】:

    由于所有元素都继承自UIView,你可以试试

    extension UIView {
     func addUnderline() {
       // create underline view add it with addSubview
     }
    }
    

    你可以从任何元素调用它

    UIButton().addUnderline()
    UILabel().addUnderline()
    

    等等

    【讨论】:

      【解决方案2】:

      如果你真的想使用 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)
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-19
        相关资源
        最近更新 更多