UIView不会识别子视图

时间:2013-07-17 05:26:58

标签: ios objective-c cocoa-touch

我需要以编程方式创建一个带有UILabel子视图的UIView,因为它比动画更好地运行IB。我不能让UIView识别出UILabel。这是我在viewDidLoad中的代码:

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(764, 94, 200, 100)];
[label setText:@"Hello"];
[label setTextColor:[UIColor redColor]];
[label setBackgroundColor:[UIColor clearColor]];

UIView *hintView = [[UIView alloc]initWithFrame:CGRectMake(764, 94, 240, 198)];
[hintView setBackgroundColor:[UIColor colorWithRed:(34/255.f) green:(59/255.f) blue:(27/255.f) alpha:(255/255.f)]];

[hintView addSubview:label];
[self.view addSubview:hintView];

NSLog(@"subview %@", hintView.subviews);

由于

3 个答案:

答案 0 :(得分:3)

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(764, 94, 200, 100)];

您正在设置宽框架尝试此

 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];

答案 1 :(得分:1)

yourLable.frame.origin.x

之间更改(0) to (320 - withOfYourLabel)

以上代码与您的自定义UIView 相同(设置X

如果您想获得自定义视图的子视图,请按照

进行操作
for(UIView *subView in hintViewsubviews)
{
     /// here you got all subview of hintView

     if([subView isKindOfClass:[UILabel class]])
     {
            // here you can also check that subView is UILabel or not ?
     }
}

答案 2 :(得分:0)

您正在为UIView和Label.bcz采用相同的帧大小,因为您没有获得正确的输出。请参阅我对您编写的更改并尝试此操作

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(hintView.frame.origin.x+15, hintView.frame.origin.y+50, hintView.frame.size.width-60, hintView.frame.size.height-100)];
[label setText:@"Hello"];
[label setTextColor:[UIColor redColor]];
[label setBackgroundColor:[UIColor clearColor]];

UIView *hintView = [[UIView alloc]initWithFrame:CGRectMake(764, 94, 240, 198)];
[hintView setBackgroundColor:[UIColor colorWithRed:(34/255.f) green:(59/255.f)    blue:(27/255.f) alpha:(255/255.f)]];

[hintView addSubview:label];
[self.view addSubview:hintView];

NSLog(@"subview %@", hintView.subviews);