Swift UITableView

作者: isletn | 来源:发表于2017-06-09 13:26 被阅读86次

UITableView在Swift中的使用

Swift是苹果在2014年WWDC上发布的新开发语言,至今已经有3年的历史,趋于成熟。之前因为种种原因一直没有上手,现在整天无所事事,就想着不如做点什么吧。OK,我们从UITableView开始学习Swift, 基础语法部分看官方文档就行了,看不懂?下面放中文链接。

创建UITableView, 我们有两种方式可以选择:Storyboard 与 纯代码,让我们一一介绍吧。


Storyboard创建UITableView

  • 1.拖UITableView


    将UITableView拖到ViewController上.png

    给上约束


    QQ20170609-102510.png
  • 2.拖Cell(给Cell拖子控件)
给�TableView添加Cell .png
  • 3.给Cell一个重用标识(随意字符串)
Cell标识.png
  • 4.拖TableView的代理
    右键按住TableView并往上面的ViewController拖,出现黑色对话框,左键选择dataSource与delegate(左边出现小白点标识成功)


    image.png
  • 5.给TableView拖一个引用到ViewController
image.png
  • 6.在控制器中遵守协议实现代理
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
}

纯代码创建UITableView

    1. 首先我们使用懒加载创建一个TableView对象,懒加载在Swift中的关键字为:lazy
// 懒加载
    lazy var zTableView: UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 64 - 49), style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 44
        return tableView
    }()
    1. 遵守UITableView的两个协议UITableViewDelegate,UITableViewDataSource
      Swift遵守协议的方式跟OC略有不同,格式如下:
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
}
    1. 实现代理方法
//Mark - UITableIView DataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell")
        cell.textLabel!.text = "ABCDEFG"
        return cell
    }
    1. 最后,在ViewDidLoad方法中将我们创建的TableView添加为self.View的子视图;
override func viewDidLoad() {
        super.viewDidLoad()
        self.view .addSubview(zTableView)
    }

OK,大功告成。运行一下:

image.png

学习资料,欢迎补充。
Swift学习资料
The Swift Programming Language

相关文章

网友评论

    本文标题:Swift UITableView

    本文链接:https://www.haomeiwen.com/subject/rdgxqxtx.html