Swift - 简单实现一个tableView

近期学习了一下swift,对swift做了初步了解,下面将使用swift简单实现一个tableView,如果有什么不全面或者是错误的地方请及时指正,我会及时更正.
通过实现tableView,掌握swift中创建一个工程流程,以及一些和OC不同的地方(Swift很魔性,很多地方要自己手敲,没有代码提示的).

1.创建一个空模板

这里写图片描述

2.选择语言(Swift)

这里写图片描述

3.指定根视图(Single View Application可以不用,storyBoard指定根视图)

需要注意的是:
1.swift中不再需要引入头文件,有的只是.swift
2.Swift 和 OC的区别是swift主流是点语法,OC是消息语法

        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()

        /// 指定根视图
        var main = MainViewController()
        var navi = UINavigationController(rootViewController: main)
        self.window!.rootViewController = navi


        return true
    }

4.VC实现tableView

以下几点需要注意:
1.Swift签协议之后不会像OC那样人性化提示有哪些协议方法没有实现,不会有警告,有的只是报错,让你误以为自己哪里写错了,坚信自己的思路写下去,补充完协议方法.
2.在cell的使用上和OC有一些区别
下面是代码实现:

import UIKit

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    /// 定义tabelView和数组
    var tabel:UITableView!
    var array = ["item1", "item2", "item3", "item4", "item5", "item6", "item7"]

    override func viewDidLoad() {
        super.viewDidLoad()

        /* navi显示标题 */
        title = "Swift tableView"

        /* 定义tableView */
        var rect = self.view.frame
        tabel = UITableView(frame: rect)
        tabel.registerClass(TableViewCell.self, forCellReuseIdentifier: "reuse")
        tabel.delegate = self
        tabel.dataSource = self
        self.view.addSubview(tabel)

        // Do any additional setup after loading the view.
    }

    /**
    section 数量 方法
    */
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }


    /**
    row 数量 方法
    */
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }

    /**
    row的高度 方法
    */
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 60
    }


    /**
    tableViewCell方法
    */
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        /// 定义一个cell
        var str:String = "reuse"
        var cell:TableViewCell = tableView.dequeueReusableCellWithIdentifier(str, forIndexPath: indexPath) as! TableViewCell
        if cell.isEqual(nil){

            cell = TableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: str)
        }
        /**
        cell赋值
        */
        cell.title.text = array[indexPath.row]
        return cell
    }

    /**
    Memory
    */
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

5.tableViewCell实现

以下几点需要注意:
1.cell实的时候需要重写初始化问题,初始化方法重写的时候可能会报错,报错原因:指定根视图的时候根视图直接使用的是MainViewController()函数,是不带任何参数的,而且程序运行会经过xib文件,会有遗留问题.此时需要添加一段代码解决遗留问题,点击报错红点,自动补齐要填充的代码.
下面是代码实现:

import UIKit

class TableViewCell: UITableViewCell {

    var title:UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    /**
    初始化方法
    */
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        if !self.isEqual(nil){
        title = UILabel(frame: CGRectMake(20, 20, 200, 30))
            self.contentView.addSubview(title)
        }
    }

    /**
    报错修复的  我也不知道是什么鬼
    */
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

6.运行结果

运行结果截图:
这里写图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UITableView循环滚动可以通过以下步骤实现: 1. 首先,创建一个UITableView并设置其数据源和代理。 2. 然后,创建一个数组来存储要显示的数据。 3. 实现UITableViewDataSource协议中的方法tableView(_:numberOfRowsInSection:),返回一个比实际数据量多的数值,例如10倍于实际数据量。 4. 实现tableView(_:cellForRowAt:)方法,在该方法中设置cell的内容,需要根据cell的indexPath.row来获取数据,应该将indexPath.row对实际数据量取模,以保证循环滚动。 5. 实现tableView(_:willDisplay:forRowAt:)方法,在该方法中判断当前cell是否为最后一行,如果是,则将tableView的contentOffset设置到第一行的位置,以实现循环滚动。 下面是一个简单实现代码: ```swift class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var data = ["A", "B", "C", "D", "E"] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count * 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = data[indexPath.row % data.count] return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let lastRowIndex = tableView.numberOfRows(inSection: 0) - 1 if indexPath.row == lastRowIndex { let firstIndexPath = IndexPath(row: 0, section: 0) tableView.scrollToRow(at: firstIndexPath, at: .top, animated: false) } } } ``` 在这个例子中,我们将数据循环滚动10次,即实际数据量为5个,但是显示了50个cell,可以通过手动滑动tableView来验证循环滚动效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值