looping through subviews or a view

一世执手 提交于 2019-12-25 07:52:16

问题


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

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.


回答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.

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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/4779048/looping-through-subviews-or-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!