如何使用帧大小从 ViewController 调用自定义 UIView

How to Call the Custom UIView from ViewController using Frame Size

我想显示 CustomUIView 来自我的 ViewController。如何使用框架调用?作为新手,我对框架感到困惑。 我的主题是,我想在 y 值 150 的 ViewController 中显示 LoginViewKarnatakausernameLabel。 这是我的代码

ViewController.m

LoginViewKarnataka *loginView = [[LoginViewKarnataka alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
[self.view addSubview:loginView];

登录视图卡纳塔克邦(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 视图中

-(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 的位置添加了一个标签。 要打印任何视图的框架,请使用以下代码。

    NSLog(@"frame : %@",NSStringFromCGRect(self.view.frame));

打印任何视图的大小

    NSLog(@"frame : %@",NSStringFromCGSize(self.view.frame.size));

你的代码没问题。所缺少的只是将 usernameLabel 作为子视图添加到您的自定义视图中。

[self addSubview:usernameLabel];

P.S。如果您需要记录任何帧值,那么您可以简单地记录视图。帧值打印在视图的描述中。如果您创建了任何复杂的 UI.

,您也可以使用 DCIntrospect 进行 UI 调试

谢谢。