IOS-Swift-cell的重用机制:

2016-11-29  本文已影响0人  任任任任师艳

AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
    self.window?.makeKeyAndVisible()
    self.window?.rootViewController = ViewController()
    return true
}

ViewController:
import UIKit
//屏幕的宽
let kScreenWidth = UIScreen.main.bounds.size.width
//屏幕的高
let kScreenHeigh = UIScreen.main.bounds.size.height

class ViewController: UIViewController,UITableViewDataSource {
var tableView : UITableView!
//
override func loadView() {
tableView = UITableView(frame: UIScreen.main.bounds, style: .grouped)
self.view = tableView
}

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.rowHeight = 184
    tableView.separatorStyle = .singleLine
    tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    tableView.separatorColor = UIColor.red

    tableView.tableFooterView = UIView()
    tableView.dataSource = self
}

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }
    /*
     UITableCell的重用
     先去重用池中找对应重用标识的cell,如果找不到就自己创建,找得到就直接拿来用
     */
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              //1.准备重用的标识
        let identifer = "cell"
        
        //2.tableView去重用池中根据重用标识取cell
        var cell = tableView.dequeueReusableCell(withIdentifier: identifer)
        //如果cell为空就自己创建
        if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: identifer)
            print("创建cell")
        }
        cell?.textLabel?.text = "行号\(indexPath.row)"
        
        
        return cell!
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

上一篇下一篇

猜你喜欢

热点阅读