我想显示 ViewController
中的 CustomUIView
。如何使用 frame 调用?作为新手,我对 Frame 感到困惑。
我的主题是,我想在 y 值 150 的 ViewController
中显示 LoginViewKarnataka
和 usernameLabel
。
这是我的代码
ViewController.m
LoginViewKarnataka *loginView = [[LoginViewKarnataka alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
[self.view addSubview:loginView];
登录 View 卡纳塔克邦(CustomUIView)
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
NSLog(@"frame==>>%f",frame);
if (self)
{
UILabel *usernameLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 100, 20)];
[usernameLabel setText:@"username"];
[usernameLabel setTextColor:[UIColor blackColor]];
}
}
最佳答案
将您的 viewController 代码更改为
LoginViewKarnataka *loginView = [[LoginViewKarnataka alloc]initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 150)];
[self.view addSubview:loginView];
在您的 LoginViewKarnataka View 中
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self setBackgroundColor:[UIColor redColor]];
UILabel *usernameLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 100, 20)];
[usernameLabel setText:@"username"];
[usernameLabel setTextColor:[UIColor blackColor]];
[self addSubview:label];
}
return self;
}
在你上面的代码中,你在 x: 20, y: 20 的位置添加了一个标签。 要打印任何 View 的框架,请使用以下代码。
NSLog(@"frame : %@",NSStringFromCGRect(self.view.frame));
打印任何 View 的大小
NSLog(@"frame : %@",NSStringFromCGSize(self.view.frame.size));
关于ios - 如何使用 Frame Size 从 ViewController 调用自定义 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917750/