Swift復習系列:Swift靜態方法的使用、通過懶加載方式創建tableView

由于之前項目用的都是Objective-C,所以swift好多東西都忘了,現在抽空再學習一下。

第一部分,創建靜態方法并使用
class MainView: UIView
{
    //Super init 方法
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        self.viewFrame = frame
    }

    //靜態方法
    class  func viewWith(frame:CGRect)-> MainView!
    {
        return MainCollectionView.init(frame: frame)
    }
}

說明

1.我們可以通過MainView.init(frame: CGRect.init(x: 0, y: 0, width: Width, height: Height))創建MainView的對象并初始化.
2.也可以通過MainView.viewWith(frame: CGRect.init(x: 0, y: 0, width: Width, height: Height))方式創建MainView的對象并初始化.

第二部分,通過懶加載方式創建tableView對象

懶加載的使用,一般為:lazy var 變量名:類型 = {操作}()
eg.

     lazy var myString:String =
    {
        return "String lazy load......"
    }()

下面是tableView的創建,

    lazy var mainList:UITableView =
    {
        ()->UITableView in
        let tempList = UITableView.init(frame: self.viewFrame!, style: UITableViewStyle.grouped)
        tempList.delegate = self
        tempList.dataSource = self
        tempList.rowHeight = 120.0
        return tempList
    }()
第三部分,創建tableView,實現代理方法
public func numberOfSections(in tableView: UITableView) -> Int 
{
   return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
   return 6
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let identifier:String = "cellIdentifier"
  var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
  if cell == nil
  {
     cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: identifier)
  }
  cell?.selectionStyle = UITableViewCellSelectionStyle.none
  cell?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
  return cell!
}


public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat 
{
   return 0.0001
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat 
{
   return 0.0001
}

我是一個swift菜鳥,還請各位多多指教。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容