Swift iOS : 一个简陋的 TableView 封装

栏目: Swift · 发布时间: 6年前

内容简介:Swift iOS : 一个简陋的 TableView 封装

UITableView功能强大,但是使用delegate设计模式的DataSource真的很不舒服。我不希望看到一堆冗长的函数签名(只能拷贝,错一点都无法执行的,但是也不会提示你)。而只是希望给它一个DataSource对象,它自己就可以显示内容即可:

tableview.Datasource = [["java","swift","js"],["java","swift","js"]]

它应该可以自己提出有两个section,每个section内的row的数量,以及要显示到Cell的内容。这是可能的,实际上,如下类Table封装完毕,使用的时候,就是可以达成希望的效果的,使用Table,你不必在自己填写这些函数:

func numberOfSections(in: UITableView) -> Int 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

代码如下:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let page = Page()
        page.view.backgroundColor = .blue
        self.window!.rootViewController = page
        self.window?.makeKeyAndVisible()
        return true
    }
}
class Page: UIViewController {
    var a : Table!
    override func viewDidLoad() {
        super.viewDidLoad()
        a  = Table()
        a.ds = [["java","swift","js"],["java","swift","js"]]
        a.frame = CGRect(x: 0,y: 50,width: 300,height: 500)
        self.view.addSubview(a)
    }
}
class Table : UITableView,UITableViewDataSource,UITableViewDelegate{
    public var  ds : [[Any]]
    override init(frame: CGRect, style: UITableViewStyle) {
        ds = []
        super.init(frame:frame,style:style)

        self.dataSource = self
        self.delegate = self
    }
    required init?(coder aDecoder: NSCoder) {
        ds = []
        super.init(coder:aDecoder)
    }
    func numberOfSections(in: UITableView) -> Int {
        return ds.count
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ds[section].count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let arr = ds
        let a = UITableViewCell(style: .default, reuseIdentifier: nil)
        a.textLabel?.text = String(describing:arr[indexPath.section][indexPath.row])
        return a
    }
}

以上所述就是小编给大家介绍的《Swift iOS : 一个简陋的 TableView 封装》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算理论导论

计算理论导论

塞普斯 / 机械工业出版社 / 2002-8 / 39.0

This book——by a noted authority and educator in the field——presents computer science theory from a uniquely intuitive,“big picture”perspective.The author grounds his clear and interesting study on ......一起来看看 《计算理论导论》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具