您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Swift 開發:UITableView 常用細節知識點整理

編輯:iOS 開發綜合

UITableView 是 iOS 開發中使用頻率最高的元件之一,但真正讓它「好用」的往往是大量細節設定。以下依主題整理常見需求與對應寫法。

隱藏分割線與多餘的 Cell

// 隱藏分割線
tableView.separatorStyle = .None

// 隱藏多餘的 cell
tableView.tableFooterView = UIView(frame: CGRectZero)

讓分割線頂到邊、並自訂顏色

畫面啟動、旋轉、尺寸位置變更、加入子視圖等時機都會呼叫 viewDidLayoutSubviews,是重設邊距的好位置:

override func viewDidLayoutSubviews() {
    tableView.separatorInset = UIEdgeInsetsZero
    tableView.layoutMargins = UIEdgeInsetsZero
    // tableView.separatorColor = UIColor.redColor()   // 分割線顏色
}

// 每個 cell 即將出現在螢幕上時都會呼叫
func tableView(tableView: UITableView,
               willDisplayCell cell: UITableViewCell,
               forRowAtIndexPath indexPath: NSIndexPath) {
    cell.separatorInset = UIEdgeInsetsZero
    cell.layoutMargins = UIEdgeInsetsZero
}

兩處都要設定,是因為前者保證初始版面正確,後者則處理重複使用與捲動過程中出現的 cell。

點擊效果與 Cell 背景

// 不要點擊效果
cell.selectionStyle = .None
// 系統預設值:.Blue(藍,預設)、.Gray(灰)、.None(無)

// 自訂選取後的背景:純色
cell.selectedBackgroundView = UIView()
cell.selectedBackgroundView?.backgroundColor = UIColor.clearColor()

// 自訂選取後的背景:圖片
cell.selectedBackgroundView = UIImageView(image: UIImage(named: article.avatarImage))

// Cell 右側的輔助提示圖示
cell.accessoryType = .DisclosureIndicator    // >
// .Checkmark               (√)
// .DetailDisclosureButton  // ! >
// .DetailButton            // !

類似按鈕的「閃一下」點擊回饋

// 在 didSelectRowAtIndexPath 中使用
// animated: false —— 一閃而過,適合伴隨畫面轉場的情境
tableView.deselectRowAtIndexPath(indexPath, animated: false)

// animated: true —— 動畫較慢,適合不轉場的情境

Cell 由下往上進場的動畫

在 viewWillAppear 中呼叫即可:

func animateTable() {
    self.tableView.reloadData()
    let cells = tableView.visibleCells
    let tableHeight = tableView.bounds.size.height

    // 先把所有可見 cell 移到畫面下方
    for i in cells {
        let cell: UITableViewCell = i as! UITableViewCell
        cell.transform = CGAffineTransformMakeTranslation(0, tableHeight)
    }

    // 依序以彈簧動畫歸位,逐格延遲形成錯落感
    var index = 0
    for a in cells {
        let cell: UITableViewCell = a as! UITableViewCell
        UIView.animateWithDuration(1.0,
                                   delay: 0.05 * Double(index),
                                   usingSpringWithDamping: 0.8,
                                   initialSpringVelocity: 0,
                                   options: [],
                                   animations: {
            cell.transform = CGAffineTransformMakeTranslation(0, 0)
        }, completion: nil)
        index += 1
    }
}

點擊 Cell 展開/收合內容

常見做法是切換 label 的 numberOfLines,並在 beginUpdates() 與 endUpdates() 之間變更,才能獲得連續的高度動畫。

// 0. 使用 SB(Storyboard)時記得先設好約束
override func viewDidLoad() {
    super.viewDidLoad()
    // 啟用自動行高
    tableView.estimatedRowHeight = 44
    tableView.rowHeight = UITableViewAutomaticDimension
}

// 1. 以字典記錄每個 cell 的展開狀態
var dict: Dictionary<Int, Bool> = [:]

// 2. 依字典決定顯示行數(假設 label 的 tag = 666,lines 在 0 與 1 之間切換)
override func tableView(tableView: UITableView,
                        cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    let label = cell.contentView.viewWithTag(666) as! UILabel
    label.text = "本文導讀 ..."
    if dict[indexPath.row] == false {
        label.numberOfLines = 0
    } else {
        label.numberOfLines = 1
    }
    return cell
}

// 3. 點擊時在 beginUpdates / endUpdates 之間切換,動畫才會連續
override func tableView(tableView: UITableView,
                        didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    let cell = tableView.cellForRowAtIndexPath(indexPath)
    let label = cell!.contentView.viewWithTag(666) as! UILabel

    tableView.beginUpdates()
    if label.numberOfLines == 0 {
        label.numberOfLines = 1
        dict[indexPath.row] = true
    } else {
        label.numberOfLines = 0
        dict[indexPath.row] = false
    }
    tableView.endUpdates()
}

沒有資料時的空狀態提示

以一個圖片加上一段文字組成簡單的空狀態視圖,並給上 tag 方便後續移除:

func showIfNoAnswer() {
    let imageView = UIImageView(frame: CGRectMake(0, 0, 60, 60))
    let image = UIImage(named: "sad")
    imageView.image = image?.imageWithRenderingMode(.AlwaysTemplate)
    imageView.tintColor = UIColor.grayColor()
    imageView.center = CGPointMake(self.view.center.x, 145)
    imageView.tag = 33          // 方便後續 removeFromSuperview
    self.view.addSubview(imageView)

    let label = UILabel(frame: .zero)
    label.text = "載入失敗"
    label.font = UIFont(name: "New Gulim", size: 20)
    label.textColor = UIColor.grayColor()
    label.textAlignment = .Center
    label.tag = 3
    label.sizeToFit()
    label.backgroundColor = UIColor.clearColor()
    label.center = CGPointMake(self.view.center.x, 200)
    view.addSubview(label)
}

實作時有兩個容易忽略的點:一是空狀態視圖應在資料載入完成後依結果決定顯示或移除,避免殘留;二是若使用 imageWithRenderingMode(.AlwaysTemplate),圖片會改用 tintColor 上色,這在需要更換主題色時相當方便。

註:本文範例採用早期 Swift 語法(如 CGRectZero、UITableViewAutomaticDimension、大写列舉成員),實際開發請對照當前版本調整。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved