swift纯代码实现UITableview总结一

在swift中没有了宏定义这个概念,所以在获取屏幕宽高时,可以设置其为常量

let SRC_WIDTH = UIScreen.main.bounds.width
let SRC_HEIGHT = UIScreen.main.bounds.height

swfit创建UITableView和OC中差不多,主要是语法发生了改变的,还有一点就是拆解包问题,不过一般编译器会给出提示

你要实现UiTableView,肯定就少不了要实现它的相关代理方法,在swift中不需要尖括号,只需要在继承的类后面用逗号隔开就可以来,如下所示:

class TableViewController:UIViewController,UITableViewDataSource,UITableViewDelegate{},这是系统会报错,不用管,因为你还没有实现它的代理和协议的;

声明UITableView

var  tableView: UITableView!

在初始化UITableView,如下:

    /**
     *  创建UITableView
     */
   func tableViewTest() -> UITableView{
        
        if tableView == nil {
            tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SRC_WIDTH, height: SRC_HEIGHT), style: .plain)
            tableView?.delegate = self
            tableView?.dataSource = self
            tableView?.showsHorizontalScrollIndicator = false
            tableView?.showsVerticalScrollIndicator = false
            tableView?.bounces = false
            tableView?.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))//去除多余的下划线
        }
        return tableView!
    }

UITableView已经创建好了,接下来的就是要实现它的数据源方法的:

分别是:

//返回cell的显示的数据

func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) ->UITableViewCell{}

//返回当前的Section中row行数

 func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int{}

//返回当前几个Section

func numberOfSectionsInTableView(tableView:UITableView) ->Int { }

//选中时方法

func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath){}

显示数据源方法如下:

   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "CELL")
           if cell == nil {
               cell = UITableViewCell(style: .default, reuseIdentifier: "CELL")
           }
//        cell!.selectionStyle = .none
        cell!.textLabel?.text = items[indexPath.row]
       
       return cell!
    }

效果图如下所示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值