我正在使用UITextView,并将UITextViewDelegate连接到视图控制器。当用户单击TextView时,我在文本视图上有一个“占位符”标签,我希望根据用户在文本视图中是否有任何文本来隐藏/取消隐藏它。但是,在UITextViewDelegate textViewDidBeginEditing和textViewDidEndEditing方法中执行UI操作似乎存在问题。在单元测试中,一切都运行得很好,但在运行应用程序时,UI不会更新。我甚至尝试过将UI包装在dispatch_async块中以强制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
}
}发布于 2015-02-03 02:05:03
与使用委托方法相比,我使用NSNotificationCenter通知要好得多。我将分享obj-c代码,但在Swift中也应该可以很好地工作。
我在UITextView上使用了一个名为_placeholderLabel的单独的UILabel来处理这个问题。
这是在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);
}
}https://stackoverflow.com/questions/28282546
复制相似问题