我正在使用UITextView并将UITextViewDelegate附加到View Controller。当用户点击TextView时,我有一个"占位符"在文本视图上标记我要隐藏/取消隐藏,具体取决于用户是否在文本视图中有任何文本。但是,在UITextViewDelegate textViewDidBeginEditing和textViewDidEndEditing方法中执行UI操作似乎存在问题。在单元测试中,一切运行正常,但在运行应用程序时,UI不会更新。我甚至尝试在dispatch_async块中包装UI来强制UI线程,但它似乎缓慢而变化无常(有时它有效,有时它不会)。有没有人见过这个?我错过了一些公然在我面前的东西吗?
public func textViewDidBeginEditing(textView: UITextView) {
switch(textView) {
case self.descriptionTextView:
self.activeTextView = self.descriptionTextView
break
case self.detailTextView:
self.activeTextView = self.detailTextView
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.detailsRequiredButton!.hidden = true
})
break
default:
break
}
}
答案 0 :(得分:0)
使用NSNotificationCenter
通知,我运气好得多,而不是使用委托方法。我将分享obj-c代码,但也应该在Swift中正常工作。
我在UILabel
上使用名为_placeholderLabel
的单独UITextView
处理此问题。
这是UITextView
的子类,但我没有看到为什么它不能真正改变UITextView
的内容/颜色的原因。您需要检查_placeholderLabel
中字符串的范围,如果您没有更多逻辑并且有人实际输入了该字符串,则会遇到麻烦。实际生产代码中还有其他代码,但不是'这里显示的是textViewDidEndEditing:
和textViewDidChange:
看起来完全相同的原因。
- (void)addObservers
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
- (void) removeObservers
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidEndEditingNotification object:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:self];
}
- (void) textViewDidEndEditing:(NSNotification *) notification
{
if ([notification object] == self)
{
_placeHolderLabel.hidden = ([[self text] length] > 0);
}
}
- (void) textViewDidChange:(NSNotification *) notification
{
if ([notification object] == self)
{
_placeHolderLabel.hidden = ([[self text] length] > 0);
}
}