内容简介: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 封装》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 封装JDBC—非框架开发必备的封装类
- SpringBlade 2.3.2 发布,增加 OSS 封装及单元测试封装
- SpringBlade 2.3.2 发布,增加 OSS 封装及单元测试封装
- docker 封装 alinode
- 封装Apk签名工具
- axios封装笔记
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Head First HTML5 Programming
Eric Freeman、Elisabeth Robson / O'Reilly Media / 2011-10-18 / USD 49.99
What can HTML5 do for you? If you're a web developer looking to use this new version of HTML, you might be wondering how much has really changed. Head First HTML5 Programming introduces the key featur......一起来看看 《Head First HTML5 Programming》 这本书的介绍吧!