iOS開發tips-神奇的UITableView

概述

UITableView是iOS開發中使用頻率最高的UI控件,在前面的文章中對於UITableView的具體用法有詳細的描述,今天主要看一些UITableView開發中的常見一些坑,這些坑或許不深,可是若是開發中注意不到的話每每比較浪費時間。html

神奇的section header

事情的原由是一個網友說要實現一個相似下圖界面,可是不論是設置sectionHeaderHeight仍是代理方法中實現func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int)都沒法調整Section Header的默認高度。並且他還試過經過func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?自定義一個header也是無濟於事。
Blog_iOS_tTps_UITableView_UITableViewDemo1swift

其實這個問題解決起來並不複雜,只要設置sectionFooterHeight爲0便可(固然對應經過代理方法也是能夠的)。默認狀況下分組樣式UITableView的section header和section footer是由一個默認高度的,並不爲0。app

import UIKit

private let ProfileTableViewControllerCellReuseIdentifier = "ProfileTableViewCell"
class ProfileTableViewController: UIViewController {
    
    // MARK: - Nested type
    struct ProfileData {
        var title:String!
        var content:String!
    }

    // MARK: - TableView life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setup()
        self.loadData()
    }

    // MARK: - Private method
    private func setup() {
        self.view.backgroundColor = UIColor.gray
        self.tableView.register(ProfileTableViewCell.self, forCellReuseIdentifier: ProfileTableViewControllerCellReuseIdentifier)
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(0.0)
        }
        
    }
    
    private func loadData() {
        self.data.removeAll()
        
        let row1 = ProfileData(title: "Name", content: "Kenshin Cui")
        let row2 = ProfileData(title: "ID", content: "kenshincui")
        let section1 = [row1,row2]
        
        let row3 = ProfileData(title: "Gender", content: "Male")
        let row4 = ProfileData(title: "Region", content: "China")
        let section2 = [row3,row4]
        
        
        let row5 = ProfileData(title: "What's Up", content: "We're here to put a dent in the universe。 Otherwise why else even be here?")
        let section3 = [row5]
        
        self.data.append(section1)
        self.data.append(section2)
        self.data.append(section3)
        
        self.tableView.reloadData()
    }
    
    // MARK: - Private property
    private lazy var tableView:UITableView = {
        let temp = UITableView(frame: CGRect.zero, style: .grouped)
        temp.estimatedRowHeight = 50
        temp.sectionFooterHeight = 0
        return temp
    }()

    fileprivate var data = [[ProfileData]]()

}


extension ProfileTableViewController:UITableViewDataSource, UITableViewDelegate{
    // MARK: - Table view data source
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionData = self.data[section]
        return sectionData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: ProfileTableViewControllerCellReuseIdentifier, for: indexPath) as? ProfileTableViewCell {
            let dataItem = self.data[indexPath.section][indexPath.row]
            cell.title = dataItem.title
            cell.content = dataItem.content
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - Table view delegate
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return CGFloat.leastNormalMagnitude
        }
        return 8.0
    }
}

數據源和代理方法的自動調用

一樣是上面的代碼,若是去掉loadData()方法後面的reloadData()調用你會發現整個界面不會有任何異常現象,數據能夠照樣加載,也就是說數據源方法和代理方法會正常調用加載對應的數據。這是爲何呢?
事實上相似於func numberOfSections(in tableView: UITableView) -> Int等方法並非只有reloadData()等方法刷新的時候纔會調用,而是在已經設置了dataSource和delegate後佈局變化後就會調用。所以即便註釋掉上面的reloadData()方法界面仍然不會有變化。
要驗證這個結論能夠延遲設置數據源和代理(注意:手動更新界面佈局setNeedsLayoutlayoutIfNeeded),或者最簡單的方式就是旋轉屏幕會發現func numberOfSections(in tableView: UITableView) -> Intfunc tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat等方法都會調用。除此以外,你也會發現func numberOfSections(in tableView: UITableView) -> Int其實並不止一次調用,系統內部爲了肯定整個佈局自己對它就存在着調用。async

分割線左側對齊

貌似蘋果的設計分割就建議你將分割線左側留出必定的間距,但在實際開發過程當中卻不多見設計師會這麼作。要讓分割線左側對齊對於當前iOS 10來講應該是再簡單不過,只要設置UITableView的separatorInset = UIEdgeInsets.zero便可(若是僅僅想要控制器某個UITableViewCell的分割線則直接設置UITableViewCell的separatorInset,固然這種方式對於.grouped風格的UITableView而言沒法修改Section頂部和底部分割線)。不太低版本的iOS就要複雜一些,例如iOS 7除了以上設置還要設置UITableViewCell的separatorInset;而iOS 八、9還要再設置UITableView的layoutMargins等。ide

固然,若是你但願控制右側的間距,仍然能夠調整separatorInset的right便可,不過調整top、bottom應該不會生效。佈局

移除多餘的行

不妨將上面代碼修改成.plain風格的UITableView,此時會發現因爲數據後面多了不少多餘的空行。移除這些空行的方法也很簡單,那就是設置tableFooterView = UIView()便可(若是設置view的高度爲CGFloat.leastNormalMagnitude則不顯示最後面的一條分割線)。固然,默認狀況下style爲.plain則每一個section的上下均不存在分割線。ui

注意:.plain風格的UITableView設置sectionFooterHeight不起做用,必須經過func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat代理方法設置。spa

.plain下禁用section header懸停

有時候你不得不用.plain Style,由於這樣一來默認Section Header就有懸停效果,可是有時候你只是想要使用.plain樣式卻不想顯示懸停效果,這時你必須禁用這個效果。
固然可使用不少黑科技來禁用懸停效果,可是最簡單的方式應該是直接將header隱藏起來:經過設置tableViewHeader高度等同於section header的高度,而後設置tableView的contentInset讓它偏移到上方,這樣一來當滾動到section header懸浮時出現的位置不是0而是被隱藏起來的偏移位置。設計

import UIKit

private let ProfileTableViewControllerCellReuseIdentifier = "ProfileTableViewCell"
class ProfileTableViewControllerWithPlain: UIViewController {
    
    // MARK: - Nested type
    struct ProfileData {
        var title:String!
        var content:String!
    }

    // MARK: - TableView life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setup()
        self.loadData()
    }

    // MARK: - Private method
    private func setup() {
        self.view.backgroundColor = UIColor.gray
        self.tableView.register(ProfileTableViewCell.self, forCellReuseIdentifier: ProfileTableViewControllerCellReuseIdentifier)
        self.tableView.estimatedRowHeight = 50
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(0.0)
        }
        
        // disable section header sticky
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 8.0))
        self.tableView.tableHeaderView = headerView
        self.tableView.contentInset.top = -8.0
        
    }
    
    private func loadData() {
        self.data.removeAll()
        
        let row1 = ProfileData(title: "Name", content: "Kenshin Cui")
        let row2 = ProfileData(title: "ID", content: "kenshincui")
        let section1 = [row1,row2]
        
        let row3 = ProfileData(title: "Gender", content: "Male")
        let row4 = ProfileData(title: "Region", content: "China")
        let section2 = [row3,row4]
        
        
        let row5 = ProfileData(title: "What's Up", content: "We're here to put a dent in the universe。 Otherwise why else even be here?")
        let section3 = [row5]
        
        self.data.append(section1)
        self.data.append(section2)
        self.data.append(section3)
        
//        self.tableView.reloadData()
    }
    
    // MARK: - Private property
    fileprivate lazy var tableView:UITableView = {
        let temp = UITableView(frame: CGRect.zero, style: .plain)
        temp.estimatedRowHeight = 50
        temp.tableFooterView = UIView()
        return temp
    }()

    fileprivate var data = [[ProfileData]]()

}


extension ProfileTableViewControllerWithPlain:UITableViewDataSource, UITableViewDelegate{
    // MARK: - Table view data source
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionData = self.data[section]
        return sectionData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: ProfileTableViewControllerCellReuseIdentifier, for: indexPath) as? ProfileTableViewCell {
            let dataItem = self.data[indexPath.section][indexPath.row]
            cell.title = dataItem.title
            cell.content = dataItem.content
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - Table view delegate
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return CGFloat.leastNormalMagnitude
        }
        return 8.0
    }

}

調整tableHeaderView的高度

若是你的UITableView設置了tableHeaderView的話,有事你可能喜歡動態調整tableHeaderView的高度,可是怎麼修改這個view的高度都不會生效。正確的修改方法是受限修改view的高度,而後將這個view從新設置給UITableView的tableHeaderView屬性。下面的demo演示了這一過程,經過這個demo能夠看到一個有趣的事實:若是你設置了tableHeaderView可是沒有指定高度的話,UITableView會自動給他提供一個默認高度。這在低版本的iOS系統中即便不指定tableHeaderView也會有這個一個默認高度,解決方式就是設置view的高度爲一個極小值,固然iOS 10中若是不指定則默認沒有tableHeaderView。代理

import UIKit

private let ProfileTableViewControllerCellReuseIdentifier = "ProfileTableViewCell"
class ProfileTableViewControllerWithHeader: UIViewController {
    
    // MARK: - Nested type
    struct ProfileData {
        var title:String!
        var content:String!
    }
    
    // MARK: - TableView life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setup()
        self.loadData()
        self.loadHeaderData()
    }
    
    // MARK: - Private method
    private func setup() {
        self.view.backgroundColor = UIColor.gray
        self.tableView.tableHeaderView = self.headerView
        self.tableView.register(ProfileTableViewCell.self, forCellReuseIdentifier: ProfileTableViewControllerCellReuseIdentifier)
        //        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(0.0)
        }
        
    }
    
    private func loadData() {
        self.data.removeAll()
        
        let row1 = ProfileData(title: "Name", content: "Kenshin Cui")
        let row2 = ProfileData(title: "ID", content: "kenshincui")
        let section1 = [row1,row2]
        
        let row3 = ProfileData(title: "Gender", content: "Male")
        let row4 = ProfileData(title: "Region", content: "China")
        let section2 = [row3,row4]
        
        
        let row5 = ProfileData(title: "What's Up", content: "We're here to put a dent in the universe。 Otherwise why else even be here?")
        let section3 = [row5]
        
        self.data.append(section1)
        self.data.append(section2)
        self.data.append(section3)
        
        
    }
    
    private func loadHeaderData() {
        DispatchQueue.main.asyncAfter(
        deadline: DispatchTime.now() + Double(Int64(2.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
            () -> Void in
            // set header data
            self.headerView.avatarURL = "avatar.jpg"
            self.headerView.introduction = "即便是別人看不見的地方,對其工藝也應該全力以赴!"
            self.headerView.frame.size.height = self.headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
            self.tableView.tableHeaderView = self.headerView
        }
    }
    
    // MARK: - Private property
    private lazy var tableView:UITableView = {
        let temp = UITableView(frame: CGRect.zero, style: .grouped)
        temp.estimatedRowHeight = 50
        temp.sectionFooterHeight = 0
        return temp
    }()
    
    private lazy var headerView:ProfileHeaderView = {
        let temp = ProfileHeaderView()
        return temp
    }()
    
    fileprivate var data = [[ProfileData]]()
}


extension ProfileTableViewControllerWithHeader:UITableViewDataSource, UITableViewDelegate{
    // MARK: - Table view data source
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionData = self.data[section]
        return sectionData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: ProfileTableViewControllerCellReuseIdentifier, for: indexPath) as? ProfileTableViewCell {
            let dataItem = self.data[indexPath.section][indexPath.row]
            cell.title = dataItem.title
            cell.content = dataItem.content
            return cell
        }
        return UITableViewCell()
    }
    
    // MARK: - Table view delegate
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return CGFloat.leastNormalMagnitude
        }
        return 8.0
    }

}
相關文章
相關標籤/搜索