日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

29.怎样扩展现有类功能?

發布時間:2025/3/15 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 29.怎样扩展现有类功能? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  實際項目開發中,我們經常會需要對系統的UI控件等進行封裝,以達到統一修改、重復代碼少、復用性高等效果。OC中,我們一般通過Category來給現有類添加方法;而在Swift中,我們使用Extension來擴展現有類的功能。

1.先看一個完整的擴展示例

import UIKitextension UILabel {/**創建UILabel- parameter text: 標題- parameter textColor: 標題顏色- parameter font: 標題字體- parameter superView: 父視圖- parameter constraints: 約束- returns: UILabel*/static func gof_labelWithText(text: String? = nil, textColor:UIColor? = nil, font: UIFont? = nil, superView: UIView? = nil, constraints: GofConstraintMaker? = nil) -> UILabel{let label = UILabel();label.backgroundColor = kCColor;label.text = text ?? "";label.textColor = textColor ?? kBColor;label.font = font ?? kBodyFont;label.textAlignment = .Left;label.numberOfLines = 1;if superView != nil{superView?.addSubview(label);if constraints != nil{label.snp_makeConstraints(closure: { (make) inconstraints!(make);})}}return label;} }

  【注意】:需要注意一下這里的方法參數,都是可選類型,并賦了默認值,這意味著在調用的時候可以不用傳遞該參數。

2.示例說明

  • 上面的封裝提供統一的創建UILabel方法;
  • GofConstraintMaker的定義可查看第27章內容,需要添加SnapKit庫;
  • 使用方式如下:
//完整參數調用let label1 = UILabel.gof_labelWithText("完整調用", textColor: gof_ColorWithHex(0xff0000), font: kBodyFont, superView: self.view) { (make) inmake.left.top.equalTo(10);make.right.equalTo(-10);make.height.equalTo(30);}//沒有字體顏色參數let label2 = UILabel.gof_labelWithText("沒有字體顏色", font: kNavFont, superView: self.view) { (make) inmake.left.equalTo(10);make.right.equalTo(-10);make.top.equalTo(label1.snp_bottom).offset(10);make.height.equalTo(30);}//沒有字體參數UILabel.gof_labelWithText("沒有字體", textColor: gof_ColorWithHex(0x0000ff), superView: self.view) { (make) inmake.left.equalTo(10);make.right.equalTo(-10);make.top.equalTo(label2.snp_bottom).offset(10);make.height.equalTo(30);}  

  類似的,大家可以自己嘗試實現其他常用控件的擴展。

轉載于:https://www.cnblogs.com/LeeGof/p/5684635.html

總結

以上是生活随笔為你收集整理的29.怎样扩展现有类功能?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。