iOS学习好东西小知识点

Swift复习系列:Swift静态方法的使用、通过懒加载方式创建

2017-08-29  本文已影响425人  ZYiDa

由于之前项目用的都是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菜鸟,还请各位多多指教。

上一篇 下一篇

猜你喜欢

热点阅读