我的代码:
class HomeViewController: UITableViewController {
var segmentedControl: HMSegmentedControl!
var text = [
// 名词
["音读名词","训读名词","音读与训读的分辨方法"],
// 形容词
["如何分辨形容词", "常用形容词", "形容词的变形规则"]
]
override func viewDidLoad() {
super.viewDidLoad()
configForSegmentedControl()
}
func configForSegmentedControl() {
segmentedControl = HMSegmentedControl(sectionTitles: ["名词","形容词","形容动词","片假名单词","动词","复合动词"])
segmentedControl.frame = CGRectMake(0, 0, self.view.bounds.width, 44)
segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10)
segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe
segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown
segmentedControl.addTarget(self, action: #selector(HomeViewController.segmentedControlChangedValue(_:)), forControlEvents: UIControlEvents.ValueChanged)
if let font = UIFont(name: "BigYoungMediumGB2.0", size: 15) {
segmentedControl.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: font]
}
segmentedControl.backgroundColor = UIColor.whiteColor()
segmentedControl.selectionIndicatorHeight = 3
segmentedControl.selectionIndicatorColor = UIColor.blackColor()
tableView.tableHeaderView = segmentedControl
}
func segmentedControlChangedValue(segmentedControl: HMSegmentedControl) {
print("Selected index \(segmentedControl.selectedSegmentIndex) (via UIControlEventValueChanged)")
}
}
extension HomeViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return text[segmentedControl.selectedSegmentIndex].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath:\(segmentedControl.selectedSegmentIndex)")
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = text[segmentedControl.selectedSegmentIndex][indexPath.row]
return cell
}
}
这是控制台输出:
的cellForRowAtIndexPath:0
的cellForRowAtIndexPath:0
的cellForRowAtIndexPath:0
选择索引1(通过UIControlEventValueChanged)
选定的索引0(通过UIControlEventValueChanged)
在cellForRowAtIndexPath
之前调用segmentedControlChangedValue
,这就是为什么我无法获得正确的索引来获取文本数组的元素。所以我该怎么做?
答案 0 :(得分:0)
以供评论参考: 如果你想要cellForRow中的值,那么你应该在'segmentedControlChangedValue'中重新加载tableview
一般情况下,根据选择/操作设置单元格,您应该根据需要重新加载/ beginUpdates tableview