在我的应用程序中,我以编程方式更新了 textView。实际上,我遍历 SQLITE3 DB 中的数据集并显示给定时间的特定文本。然后我想显示下一个数据集记录中的文本等等。我一直在浏览各种论坛和苹果文档,但找不到像重绘、刷新、updateTextView 等命令之类的东西。我正在处理长字符串,为什么我认为 UITextView 将是最好的显示方式。但是,如果另一个 UI 类,如 UITextField 或 UILabel 会更好、更容易地实现我正在寻找的东西,我也会使用它。没问题。
5 回答
You can force a UITextField
to repaint its text by setting its text color:
textField.textColor = [UIColor colorWithWhite:0.0 alpha:1.0];
The color doesn't need to be different, it simply needs to be a new UIColor
instance. The above code will do this. Forcing a repaint can be useful if you have overridden drawTextInRect:
and want to change the appearance of the text without changing the text itself.
For performance reasons, calling [textField setNeedsDisplay]
will not repaint (or call drawTextInRect:
) if the text has not changed.
我自己正在努力更新多行 UITextView,我从“Phil Calvin”的答案中找到了解决方案
在我的情况下,我使用textView.textColor = [UIColor blackColor];
所以,这里有一些更多的上下文可以帮助你完成任务......
- (void)textViewDidChange:(UITextView *)textView
{
// ... lots of code to calculate the correct autolayout constraints & content size
[textView setContentSize:CGSizeMake(textFitSize.width, newTextContentHeight)];
[textView.superview setNeedsUpdateConstraints];
[UIView animateWithDuration:0.3
animations:^
{
// first apply the AutoLayout to resize the UITextView
[textView layoutIfNeeded];
[textView.superview layoutIfNeeded];
}
completion:^(BOOL finished)
{
// then update the text by resetting the text colour
dispatch_async(dispatch_get_main_queue(), ^{
[textView.textColor = [UIColor blackColor];
[UIView animateWithDuration:0.3
animations:^(void) {
// do not loose the keyboard
[textView becomeFirstResponder];
}
completion:^(BOOL finished) {
// move the cursor to the bottom of the text view
textView.contentOffset = CGPointMake(0., textView.contentSize.height);
}];
});
}];
}
你的问题到底是什么?
您是在问如何在 a 中设置文本UITextView
?只需使用它的text
属性:
someTextView.text = @"Some Text";
您是在问使用UILabel
or是否“更好” UITextField
?这是一个主观的问题。这取决于您的应用程序是如何设计的,以及最适合呈现文本信息的方式。(在 a 中显示格式化的 HTMLUIWebView
是另一种选择。)
一旦你设置了这些内置类的文本,它就会知道自己更新/重绘。您无需设置文本,然后手动触发重绘或“重绘”。
[myTextView setNeedsDisplay];
行得通吗?这是告诉 iOS UIView 它需要查看重绘自身的传统方式。UIView文档包含一些很好的信息。
好的,我现在得到了解决方案。与往常一样,只要您知道如何操作,它就非常简单:-) 看起来,我对最初的问题描述不是很清楚,这里再次是功能描述:我需要我的应用程序显示我的 SQLITE3 数据库中的文本UITextView 并使用数据库中下一条记录中的文本每 2 秒更新一次该文本。所以我最初的想法是在 Select 循环中进行。带着粗犷的暗示,即视图不会更新,在完成循环之前,因为它在单个线程中运行,我开始寻找另一种解决方案,并提出了以下基于选择器的解决方案,效果非常好。
用户界面中任何对象的这种程序化和迭代更新的解决方案是这样的方法
- (IBAction)displayTextFromArray:(UIButton *)sender{
timer = [NSTimer scheduledTimerWithTimeInterval:(2.0) target:self selector:@selector(displayText) userInfo:nil repeats:YES];
}
在我的例子中,当用户触摸 UIButton 时会调用此方法。要使计划停止,需要向计时器实例发送以下消息:
[timer invalidate];
当然,我必须稍微更改我的代码以使用预定计时器运行,但从迭代的角度来看,上面的代码是触发和停止调度程序所需的一切。希望这也可以帮助其他有类似问题的人。
干杯,勒内