zoukankan      html  css  js  c++  java
  • UIKit应用

    这次我们来分享一下关于 UITableView 的一个开发小技巧, 后面我会陆续的把关于 UITableView 的其他开发小技巧补充上, 废话少说, 让我们来看看代码


    1.界面布局

    1

    关于怎么快速添加一个 UINavigationController 在上两篇文章里有讲解, 这里就不说了, 下面让我们来看看代码.


    2.实现代码

    遵守代理协议和数据源协议

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {}

    设置代理对象

        override func viewDidLoad() {
            super.viewDidLoad()
            myTableView.delegate = self
            myTableView.dataSource = self
        }

    获取属性和声明数据

        @IBOutlet weak var myTableView: UITableView!
    
        let stringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]

    实现代理方法和数据源方法

        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return stringArray.count
        }
    
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as! UITableViewCell
            cell.textLabel!.text = stringArray[indexPath.row]
            return cell
        }

    实现自定义方法

        func colorForIndex(index: Int) -> UIColor {
            let itemCount = stringArray.count - 1
            let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
            return UIColor(red: 0.8, green: color, blue: 0.2, alpha: 1.0)
        }
    
        func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
            cell.backgroundColor = colorForIndex(indexPath.row)
        }
    
        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            self.myTableView.deselectRowAtIndexPath(indexPath, animated: true)
        }

    3.最终效果

    1


    好了, 这次我们就讲到这里, 下次我们继续~~~

  • 相关阅读:
    IE6常见CSS解释BUG及hack
    超链接标签a
    图片标签img
    如何让一个元素始终在窗口水平垂直居中
    display属性及属性值
    设置省略号
    如何让一个图片垂直居中
    post与get的区别
    绝对路径与相对路径
    数组的操作方法
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4529329.html
Copyright © 2011-2022 走看看