代码说明
我对我的应用程序做了一个小更改(Swift 2.1、xCode 7.2、部署目标 8),添加了一个带有两个搜索选项的表。该行为可以映射为:
- 在
didSelectRowAtIndexPath
上,更改 ViewController 的selectedSearchOption
属性并更改keyboardType
,所有这些均基于所选元素。然后,调用reloadInputViews
(VC 的)和reloadData
(表的)。
代码
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedSearchOption = self.searchOptions[indexPath.item]
switch selectedSearchOption {
case SearchOption.ByTeam:
searchField.keyboardType = UIKeyboardType.NumbersAndPunctuation
default:
searchField.keyboardType = UIKeyboardType.Default
}
searchField.reloadInputViews()
searchOptionsTableView.reloadData()
}
- 在
cellForRowAtIndexPath
方法(随后调用,因为我调用reloadData
)上,我检查selectedSearchOption
属性以自定义所选 View 的 View 元素。
代码
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(SearchOptionCell.identifier) as! SearchOptionCell
let searchOption = self.searchOptions[indexPath.item]
cell.name.text = searchOption.rawValue
if self.selectedSearchOption == searchOption {
cell.imageView?.image = UIImage(named: "ic_done_16")
} else {
cell.imageView?.image = nil
}
return cell
}
问题:
该代码在 iPad 2 (8.3) 和 iPhone 6 (8.4.1) 上运行良好,但在 iPhone 4S(之前是 9.something,我更新到 9.3.1)上,发生了两件奇怪的事情:
reloadInputViews
没有更改用户的键盘类型(我已经尝试调用resignFirstResponder
,然后becomeFirstResponder
)。当调用
cellForRowAtIndexPath
时,selectedSearchOption
属性将保留其旧值,就像从未更改过一样。尽管很疯狂,但如果我调试didSelectRowAtIndexPath
,VC 上的值是正确的。
对我做错了什么有什么想法吗?
最佳答案
我发现了问题。
我有一个 UIKeyboardWillShowNotification
事件的监听器。
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "showKeyboard",
name:
UIKeyboardWillShowNotification,
object: nil
)
在 showKeyboard 方法中,我重置了 selectedSearchOption
值。显然,在 iOS 9 上,reloadInputViews
方法现在正在调用 UIKeyboardWillShowNotification
事件。
为了解决该问题,我现在使用在 UIKeyboardWillShowNotification
和 UIKeyboardWillHideNotification
事件中更新的标志检查键盘是否已打开。很高兴 UIKeyboardWillHideNotification
没有被 reloadInputViews
方法调用。然后,只要键盘打开,我就会重置 selectedSearchOption
属性。
关于ios - 在 iPhone 4S 上,ViewController 上的更改不会从 didSelectRowAtIndexPath 持续到 cellForRowAtIndexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36922081/