使用Playground‘玩’界面 - 2

作者: handyTOOL | 来源:发表于2016-09-12 23:43 被阅读221次

    这一篇主要说一下如何在Playground中使用ViewController。

    首先我们创建一个DemoTableViewController。

    public class DemoTableViewController : UIViewController,UITableViewDataSource {
        lazy var tableView:UITableView = UITableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        override public func viewDidLoad() {
            tableView.dataSource = self
            tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
            view.addSubview(tableView)
            self.tableView.frame = self.view.frame
        }
       
        public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 10
        }
        
        public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            cell.textLabel?.text = String(indexPath.count)
            return cell
        }
    }
    

    在这个ViewController中我添加了一个TableView。然后再使用使用Playground‘玩’界面 - 1中提到的PlaygroundPage.current.liveView就可以显示这个ViewController了。

    PlaygroundPage.current.liveView = DemoTableViewController.init()
    
    效果图

    完整代码如下:

    import UIKit
    import PlaygroundSupport
    
    public class DemoTableViewController : UIViewController,UITableViewDataSource {
        lazy var tableView:UITableView = UITableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        override public func viewDidLoad() {
            tableView.dataSource = self
            tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
            view.addSubview(tableView)
            self.tableView.frame = self.view.frame
        }
        
        public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 10
        }
        
        public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            cell.textLabel?.text = String(indexPath.item)
            return cell
        }
    }
    
    PlaygroundPage.current.liveView = DemoTableViewController.init()
    

    相关文章

      网友评论

        本文标题:使用Playground‘玩’界面 - 2

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