huy-le
5/25/2016 - 12:01 PM

UITableView+Extension.swift

extension UITableView {
    
    /**
     Use it as a trick to remove the separator lines of blank cells at the bottom of tableView.
     */
    func removeBottomSeparatorLine() {
        tableFooterView = UIView(frame: CGRect.zero)
    }
    
    func scrollToLastRowOfSection(section: Int, atScrollPosition: UITableViewScrollPosition = .Top, animated: Bool = false) {
        scrollToRowAtIndexPath(lastRowInSection(section), atScrollPosition: atScrollPosition, animated: animated)
    }
    
    func registerClass(cell: UITableViewCell.Type) {
        registerClass(cell.classForCoder(), forCellReuseIdentifier: cell.className())
    }
    
    func registerNib(cell: UITableViewCell.Type) {
        registerNib(cell.nib(), forCellReuseIdentifier: cell.className())
    }
    
    func dequeueCell<T where T: UITableViewCell, T: ClassnameStringConvertable>(forIndexPath indexPath: NSIndexPath) -> T {
        guard let cell = dequeueReusableCellWithIdentifier(T.className(), forIndexPath: indexPath) as? T else {
            preconditionFailure("Unable to dequeue \(T.description()) for indexPath: \(indexPath)")
        }
        return cell
    }
    
    func registerHeaderFooterNib(headerFooterView: UITableViewHeaderFooterView.Type) {
        registerNib(headerFooterView.nib(), forHeaderFooterViewReuseIdentifier: headerFooterView.className())
    }
    
    func registerHeaderFooterClass(headerFooterView: UITableViewHeaderFooterView.Type) {
        registerClass(headerFooterView.classForCoder(), forHeaderFooterViewReuseIdentifier: headerFooterView.className())
    }
    
    func dequeueHeaderFooter<T where T: UITableViewHeaderFooterView, T: ClassnameStringConvertable>() -> T {
        guard let view = dequeueReusableHeaderFooterViewWithIdentifier(T.className()) as? T else {
            preconditionFailure("Unable to dequeue \(T.description())")
        }
        return view
    }
    
    private func lastRowInSection(section: Int) -> NSIndexPath {
        guard let dataSource = dataSource else {
            preconditionFailure("Don't have dataSource")
        }
        return NSIndexPath(forRow: dataSource.tableView(self, numberOfRowsInSection: section) - 1, inSection: section)
    }
}