APP上面有用UITableView
實現(xiàn)的通訊錄功能,通訊錄按名字首字母分組,右邊有一列索引,點擊導(dǎo)航到對應(yīng)的組。產(chǎn)品看到別的APP上面點擊索引的時候有放大的字母顯示,就讓我給加上捂寿。效果如下:
1.png
在TableView
上面添加索引是很簡單的,只要實現(xiàn)兩個代理方法就行
optional public func sectionIndexTitles(for tableView: UITableView) -> [String]?
// return list of section titles to display in section index view (e.g. "ABCD...Z#")
optional public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int
// tell table which section corresponds to section title/index (e.g. "B",1))
第一個方法返回一個String
數(shù)組,TableView
就會依次顯示在索引上迫筑。
第二個方法返回當(dāng)點擊到索引的第index個索引時,跳到哪一組庸疾。
實現(xiàn)完這兩個方法TableView
索引的功能就做完啦俗冻。
UITableView
還有屬性設(shè)置索引樣式
-
sectionIndexColor
: 索引顏色 -
sectionIndexBackgroundColor
: 索引條背景顏色 -
sectionIndexMinimumDisplayRowCount
: 個數(shù)大于該值才會顯示索引,默認(rèn)為0。 -
sectionIndexTrackingBackgroundColor
: 觸摸時索引條背景的顏色
添加懸浮View
先說說我的思路吧,自定義索引條當(dāng)然可以實現(xiàn),作為一個懶惰的人,我肯定不想自定義索引,因為代理方法實現(xiàn)索引如此簡單拭荤。自己自定義的索引條當(dāng)然相加什么都行,但是需要和TableView
連接起來,這里有一定工作量。然后就開始了偷懶之旅:
- 首先在上面第二個代理方法在點擊索引的時候會調(diào)用,而且還拿得到當(dāng)前點擊的索引,就想著在這里添加
浮動View
顯示,奈何沒有方法監(jiān)聽到手指離開索引,不知何時隱藏浮動View
震叮。 - 不知何時隱藏
浮動View
,于是就想到了定時隱藏,切換到其他索引的時候就關(guān)閉動畫再加一個新的,似乎可以實現(xiàn),但是手指要是一直點擊在同一個索引上時,浮動View
需要一直顯示,可是依然監(jiān)聽不到這種情況,定時隱藏也不適用胧砰。 - 不知道手指何時離開索引,就想著監(jiān)聽手指何時離開
TableView
隱藏浮動View
,于是就想到touchesEnded
方法,需要自定義TableView
,嘗試了一下發(fā)現(xiàn)也很復(fù)雜,并且TableView
不會響應(yīng)這個方法。似乎是TableView
會吸收touch事件,有辦法解決,但是會跟TableViewCell
上面的按鈕沖突苇瓣。 - 只能用最后一招了,在
TableView
索引條上面加上Pan手勢,索引的高度固定不能修改,索引都居中,可以根據(jù)手指在索引條的位置來判斷點擊的是哪個索引尉间。接下來就是找到這個索引條了,找了一下UITableView
的頭文件,不出所料沒找到索引條。于是把TableView
的subViews
打印下來看看击罪。
果然發(fā)現(xiàn)了一個UITableViewIndex
私有類,應(yīng)該就是它了哲嘲。
<UITableViewIndex: 0x1558b3210; frame = (399 0; 15 578); opaque = NO; layer = <CALayer: 0x15589f350>>
于是就在sectionIndexTitles
方法添加手勢
for view in tableView.subviews {
if view.width == 15 {
view.gestureRecognizers = nil
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(indexTitlesPan(_:))))
}
}
然后實現(xiàn)Pan方法
@objc fileprivate func indexTitlesPan(_ rgz: UIPanGestureRecognizer) {
// 計算點擊到哪個索引
let count = (addressBooksByLetter?.count ?? 0)+1
let indexHeight = CGFloat(count)*IndexTitlesViewHeight
let tableViewHeight = kAppHeight-NavigationH-50
let startY = (tableViewHeight-indexHeight)/2
let offsetY = rgz.location(in: rgz.view).y
var selectIndex = Int((offsetY - startY)/IndexTitlesViewHeight)
if selectIndex < 0 {
selectIndex = 0
} else if selectIndex > count-2 {
selectIndex = count-2
}
// 結(jié)束隱藏懸浮View
if rgz.state == .ended {
alertLabel.isHidden = true
} else {
alertLabel.text = addressBooksByLetter?[selectIndex].name
alertLabel.isHidden = false
}
// 因為pan手勢會吸收索引原本點擊事件,需要自行實現(xiàn)tableView跳轉(zhuǎn)
tableView.scrollToRow(at: IndexPath(row: 0, section: selectIndex), at: .top, animated: false)
}
大功告成!