循环遍历子视图或视图 [英] looping through subviews or a view

查看:132
本文介绍了循环遍历子视图或视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做错了什么?观点在IB中设置。 answersView有3个子视图。每个都是UITextViews。但我得到一个答案,我无法在UIView上设置文字。提前致谢。

What am I doing wrong? The views are set up in IB. There are 3 subviews of answersView. Each are UITextViews. But I get an answer that I can't set text on a UIView. Thanks in advance.

int i;
for (i=0; i<[[[self answersView]subviews]count]; i++) 
{
    UITextView *currentText = (UITextView *)[[self answersView] viewWithTag:i];
    NSString *answer = [[self answersArray] objectAtIndex:i];
    [currentText setText:answer];
}

错误是:由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因: ' - [UIView setText:]:无法识别的选择器发送到实例0x5f56330'

The error is: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setText:]: unrecognized selector sent to instance 0x5f56330'

好的我已经更新了代码

int i;
for (i=0; i<[[[self answersView]subviews]count]; i++) 
{
    UITextView *currentText = (UITextView *)[[self answersView] viewWithTag:i+1];
    if ([currentText isKindOfClass:[UITextView class]]) {
        NSString *answer = [[self answersArray] objectAtIndex:i];
        [currentText setText:answer];
        NSLog(@" tag %d",i + 1);
    }
}

感谢所有帮助。

推荐答案

你想在你的for循环中添加一个 -1 ,这样你就不去了出界。此外,您需要检查子视图是否为文本字段对象,否则您将在其他类型的视图上设置文本。

You want to add a -1 in your for loop so you don't go out of bounds. Also, you need to check that the sub view is a textfield object, or else you're going to be setting text on some other kind of view.

代码:

for (int i=0; i<[[[self answersView]subviews]count]-1; i++) {
    if ([[[self answersView] viewWithTag:i] isKindOfClass:@"UITextView") {
        UITextView *currentText = (UITextView *)[[self answersView] viewWithTag:i];
        NSString *answer = [[self answersArray] objectAtIndex:i];
        [currentText setText:answer];
    }
}

这篇关于循环遍历子视图或视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆