swift开发的小坑

313 阅读1分钟

####swift 几个比较好的UI库 swift UI库

###1.tableView的代理方法

在swift中代理变得更加重要,当在继承代理的时候,代理的require方法必须实现,否则直接就报错。 但是这个报错一点也不友好,下面这个例子就是先写了代理,还没有实现其代理方法,引入的时候直接报错了.But,在Xcode 9版本修复这个问题,错误提示很友好了。

代理没实现.png

这报错提示“Type 'UIViewController' does not conform to protocol 'UITableViewDataSource'” 简直一脸懵逼啊,查了好久才知道原来是代理方法没有写,写了其require方法就好了。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell: UITableViewCell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = "row + \(indexPath)"
        return cell
    }

####2.如果定义tableView是grouped类型,默认是有sectionHeader 和 sectionFooter的,即使你没有实现,也是有一个灰色View在上面。如图

sectionHeader 和 FooterView.png

这时候,你不想要header或是footerView,

1.将tableView定义成plain类型,默认就没有header和footerView了 2.实现header或footerView的高度代理方法,设置一个极小值即可

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

####3.tableView 注册cell方法

        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
或者
        collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")

暂不知道什么区别,都可以好像。 自定义cell注册的时候好像就要用self了。

swift中对基本知识的要求更高了,基本知识必须掌握牢。

因为这里对了好多安全机制,有些异常不会报错,但是就是不会出你要的结果,很难排查,所以要有更好的基础知识。 遇见的小坑,以后慢慢填坑。。