开发者

looping through subviews or a view

What am I doing wrong? The views are set up in IB. There are 3 subviews of answersView. Each are UITextViews. But I g开发者_高级运维et 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];
}

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

Okay I've updated the code

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);
    }
}

Thanks for all the help.


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.

Code:

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];
    }
}


Hey there, I think that your code is pretty prone to errors because it relies upon the fact that the views are always going to have a tag number set. You could do two things in my opinion:

1) Check prior to calling setText that currentText is a valid UITextView doing something like this:

if ([currentText isKindOfClass:[UITextView class]])
{
   ...
   [currentText setText:answer];
   ...
}

2) What I actually think it is better, loop through the subviews this way:

for (UITextView* currentText in [[self answersView]subViews])
{
   ...
   [currentText setText:answer];
   ...
}


Set the tag value greater than 0. Loop from 1 to array count.

The super view will have the default tag value as 0. Because of that only you are getting such an error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜