1

我需要以编程方式创建一个带有 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);

谢谢

4

3 回答 3

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

你正在设置宽框架试试这个

 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
于 2013-07-17T05:31:26.370 回答
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 ?
     }
}
于 2013-07-17T05:33:05.770 回答
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);
于 2013-07-17T05:48:54.570 回答