美文网首页iOS学习
Swift初学 tableView

Swift初学 tableView

作者: 慌莫染 | 来源:发表于2018-03-02 15:51 被阅读10次

记录下Swift学习历程

1.创建Swift项目

image image image image

2.写入一些数据


class ViewController: UIViewController {

    let btnStarTag:Int = 1000//定义btn起始tag值

    //数组,其中的数据是(sting,sting)格式的元组

    //其内容为title名 和对应的点击显示

    let Name_linkes_tuples:[(String,String)] =

        [

            ("第1行","1"),

            ("第2行","2"),

            ("第3行","3"),

            ("第4行","4"),

        ]

    let table:UITableView = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

}

这里有个注意事项,table的初始化我写在了class区间内,不在method方法内,如果在oc这是绝对不允许的。写在class区间的数据在整个类中可以访问,而写在method内的数据只能在这个method内使用。(btnStartTag、name_links_tuples也是一样)

在swift中允许这样的特例,即允许在method之外调用方法来初始化数据,但其他方法调用仍需要写在method内。

为了说明这种特例,我们尝试调用table.delegate

image

2.接下来,把table添加到视图界面上

image

3.添加协议

image

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Name_linkes_tuples.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
        let title:String = Name_linkes_tuples[indexPath.row].0
        cell.textLabel!.text = title

        //每行一个按钮
        let btn:UIButton = UIButton(type: UIButtonType.custom)
        btn.frame = CGRect(x: UIScreen.main.bounds.width-100, y: 10, width: 80, height: 50)
        btn.setTitle(Name_linkes_tuples[indexPath.row].1, for: UIControlState.normal)
        btn.setTitleColor(UIColor.black, for: UIControlState.normal)
        btn.backgroundColor = UIColor.red
        btn.tag = btnStarTag+indexPath.row
        btn.addTarget(self, action: #selector(self.btnClick), for: UIControlEvents.touchUpInside)
        cell.contentView.addSubview(btn)
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

//禁止cell被点击

    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

        return nil

    }

4.实现btn的action方法

我们在每个cell上添加了action方法,接下来就要实现这个action


 func btnClick(sender:UIButton) {
        print("btn click\(sender.tag)")
    }

5.最终效果

image

感谢白马斩尘_Pinch

参考链接https://www.jianshu.com/p/6a5596c772be

相关文章

网友评论

    本文标题:Swift初学 tableView

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