UIView子视图没有响应更改

时间:2011-03-10 19:23:25

标签: iphone objective-c ios uiview subview

我正在学习如何处理子视图,而且我很难操纵其中一个的位置。每个子视图都有一个唯一的标记。值得注意的是,我在UITableCell中搜索子视图,UITableView大约有5行。

如果我这样做:

UIView *mike = [self.view viewWithTag:6];
mike.frame = CGRectMake(250, 5, 25, 20);
mike.backgroundColor = [UIColor redColor];
NSLog(@"mike=%@ tag=%d",[[mike class] description], [mike tag]);

或:

UILabel *label = (UILabel *)[self.view viewWithTag:6];
label.frame = CGRectMake(250, 5, 25, 20);
label.backgroundColor = [UIColor redColor];
NSLog(@"label=%@ tag=%d",[label text], [label tag]);

子视图不会改变位置,但是如果我使用下面的代码搜索它,它确实有效。

for (UIView *subview0 in [self.view subviews])
{
  for (UIView *subview1 in [subview0 subviews])
  {
    for (UIView *subview2 in [subview1 subviews])
    {
      if ([[[subview2 class] description] isEqualToString: @"UILabel"]) 
      {
        [subview2 setText:@"mike"];
        subview2.frame = CGRectMake(250, 5, 25, 20);
        subview2.backgroundColor = [UIColor redColor];
      }
    }
   }
 }

任何帮助非常感谢。

麦克

编辑:从执行中的控制台

2011-03-10 19:53:42.344 mike = UILabel tag = 6 0x4b59610
2011-03-10 19:53:42.344 label = 842 tag = 6 0x4b59610
2011-03-10 19:53:42.345 0-subview = PerformAnalysisCustomCell tag = 0
2011-03-10 19:53:42.345 1-subview = UIGroupTableViewCellBackground tag = 0
2011-03-10 19:53:42.346 2-subview = UIView tag = 0 0x4d62910
2011-03-10 19:53:42.349 1-subview = UITableViewCellContentView tag = 0
2011-03-10 19:53:42.349 2-subview = UILabel tag = 0 0x4b51320
2011-03-10 19:53:42.350 2-subview = UILabel tag = 1 0x4b59290
2011-03-10 19:53:42.350 2-subview = UILabel tag = 2 0x4b59370
2011-03-10 19:53:42.358 2-subview = UILabel tag = 3 0x4b59410
2011-03-10 19:53:42.359 2-subview = UILabel tag = 4 0x4b594b0
2011-03-10 19:53:42.360 2-subview = UILabel tag = 5 0x4b59560
2011-03-10 19:53:42.360 2-subview = UILabel tag = 6 0x4b59610

将%p放入NSLog后,您可以将内存地址相同。其他tag = 6行有不同的地址,所以我应该期望至少该单元格移动。

3 个答案:

答案 0 :(得分:0)

我更喜欢子类UITableViewCell,然后我可以通过属性访问我想要的内容。我不喜欢 -viewWithTag:,它之前给我带来了问题,并且使代码难以管理。

答案 1 :(得分:0)

你的前两个例子完全相同。静态类型(UIView * vs UILabel *)不会更改编译器在这种情况下生成的代码。

第三个例子应该是NSLog操作的每个视图。也许标签没有设置。

使用if (subview2.tag == 6)之类的内容进行检查也是有意义的,看看是否有多个具有相同标签的视图(听起来像是这样)。

您的日志消息还可以打印视图描述(或简单地以“%p”格式显示视图的地址),以查看您使用的视图是否相同。

答案 2 :(得分:0)

您需要在每个单元格上运行viewWithTag语句,而不是在整个tableView上运行。这应该很可能在cellForRowAtIndexPath中设置,然后您将在需要时重新加载已更改的行。

相关问题