已创建的带标签的UIViews变为NULL

时间:2014-04-03 11:23:23

标签: ios iphone objective-c uiview tags

我有UIButton并点击它,执行以下块。此块会创建UITextView,并将其作为子视图添加到带有标记的新UIView。多次单击UIButton时,此代码块将执行并输出多个UIViews。

int commentCount=1;
y=0;


- (IBAction)OnClickAddAnother:(id)sender
{
     UIView *_extraCommentView=[[UIView alloc]initWithFrame:CGRectMake(0,y,280,198)];
     _extraCommentView.tag=commentCount;

     UITextView *commentTextView=[[UITextView alloc]initWithFrame:CGRectMake(0, 29, 280, 134)];
     commentTextView.backgroundColor=[UIColor colorWithRed:(195.0/255.0) green:(195.0/255.0) blue:(195.0/255.0) alpha:1];

     [_extraCommentView addSubview:commentTextView];


     UIView *previous=(UIView *)[_extraCommentView viewWithTag:1];
     UIView *next=(UIView *)[_extraCommentView viewWithTag:2];
     NSLog(@"prev  ->%@",previous);
     NSLog(@"nxt   ->%@",next);

     commentCount++;
     y+=200
}

我尝试使用代码' 1'来访问UIViews和' 2'。例如,当我单击UIButton 4次时,此块执行4次并得到此日志:

2014-04-03 16:24:15.106 SmartWatch[2465:70b] pre1-><UIView: 0x8c69440; frame = (0 -396; 280 198); tag = 1; layer = <CALayer: 0x8c6b5e0>>
2014-04-03 16:24:15.107 SmartWatch[2465:70b] nxt1->(null)

2014-04-03 16:24:16.450 SmartWatch[2465:70b] pre1->(null)
2014-04-03 16:24:16.450 SmartWatch[2465:70b] nxt1-><UIView: 0x8c4f2f0; frame = (0 -198; 280 198); tag = 2; layer = <CALayer: 0x8c55ca0>>

2014-04-03 16:24:16.642 SmartWatch[2465:70b] pre1->(null)
2014-04-03 16:24:16.642 SmartWatch[2465:70b] nxt1->(null)

2014-04-03 16:24:16.945 SmartWatch[2465:70b] pre1->(null)
2014-04-03 16:24:16.946 SmartWatch[2465:70b] nxt1->(null)

为什么UIViews带有标记&#39; 1&#39;和&#39; 2&#39;第3次和第4次点击返回NULL?

2 个答案:

答案 0 :(得分:4)

您创建的第一次迭代中的代码运行良好:

_extraCommentView with tag = 1 
commentTextView no tag 

,结果是

tag 1 - _extraCommentView which is right
tag 2 is NULL which is also right.

在第二次迭代中,您创建

_extraCommentView with tag = 2
commentTextView no tag  

结果是:

tag 1 null 
tag 2 _extraCommentView

这也是对的。

在第3次迭代中,您创建

  _extraCommentView with tag = 3
  commentTextView` no tag  

结果是:

tag 1 null 
tag 2 null

回答你的问题:

  

为什么标记为'1'和'2'的UIViews为第3和第4返回NULL   点击?

在第3和第4个按钮中单击commentCount等于3,但是NSLogs日志视图仅用于标记1和2。

答案 1 :(得分:1)

@Greg回答是正确的,如果你想要一个视图列表尝试添加到一个数组

 NSMutableArray *viewArray=[[NSMutableArray alloc]init];
- (IBAction) OnClickAddAnother:(id)sender 
{

     UIView *_extraCommentView=[[[UIView alloc]init ]initWithFrame:CGRectMake(0,y,280,198)];
    _extraCommentView.tag=commentCount;

    UITextView *commentTextView=[[UITextView alloc]initWithFrame:CGRectMake(0, 29, 280, 134)];
    commentTextView.backgroundColor=[UIColor colorWithRed:(195.0/255.0) green:(195.0/255.0) blue:(195.0/255.0) alpha:1];

    [_extraCommentView addSubview:commentTextView];

    [viewArray addObject:_extraCommentView];
    for(UIView *view in viewArray )
    {
        NSLog(@"View  ->%@",view);
    }

    commentCount++;
    y+=200;
}