最近的新项目有一个如下的界面
系统中有index的tableview
而设计的要求是这样的
设计图中有index的tableview
1.创建indexView,指定frame
// 113为导航栏高度64 + tabar高度49
let indexViewH = (kScreenH - 113) * 0.91
// 这样设置Y保证indexview居中显示
let indexViewY = ((kScreenH - 113) - indexViewH) * 0.5 + 64
let indexView = UIView(frame: CGRect(x: kScreenW - 15, y: indexViewY, width: 10, height: indexViewH))
2.根据数据源数组个数添加LetterLabel
// 获取数组个数
let count = CGFloat(self.brandList.count)
// 利用EnumerateSequence遍历可以获得带index的元组
for (index,letter) in EnumerateSequence(self.brandList.map{ $0.letter! }) {
// 设置letterLabelfram和字体颜色等
let letterLabel = UILabel(frame: CGRect(x: 0, y: indexViewH / count * CGFloat(index) , width: 12, height: indexViewH / count))
letterLabel.font = UIFont.systemFontOfSize(12)
letterLabel.textColor = QGColor.GrayColor
letterLabel.text = letter
indexView.addSubview(letterLabel)
}
3.给indexView添加手势
let touch = UITapGestureRecognizer(target: self, action: "indexViewTap:")
indexView.addGestureRecognizer(touch)
4.通过手势让tableview滚动到指定的section
// 手势响应的方法
func indexViewTap(tap: UITapGestureRecognizer) {
// 获得点击手势在indexview的坐标Y
let touchY = tap.locationInView(indexView).y
// 利用坐标Y获得一个索引也就是letterLabel在indexview的索引
let index = Int(touchY / indexView.bounds.height * CGFloat(brandList.count))
// 创建indexPath 让tableview滚动到该位置
let indexPath = NSIndexPath(forRow: 0, inSection: index)
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
}
如果你觉得这个方法不错,可以这样来使用我的代码.把UITbleview+Extension
拖入你的项目,或者只把代码拷到你写tableview分类的文件.然后在有需要设置sectionindex的控制器这样设置tableview
就可以了
// self.brandList为[String]类型的数组 我的示例代码中brandList中放的是对象,所以用map去得到一个纯字符串的数组
tableView.setIndexViewWith(self.brandList.map{ $0.letter! })
// 由于这个方法后两个参数有默认值 传和不传都可以 这句代码就是传入自定义的索引文字颜色和文字大小
tableView.setIndexViewWith(self.brandList.map{ $0.letter! }, letterColor: UIColor.grayColor(), letterFont: UIFont.systemFontOfSize(12))