ios - 如何使用 Frame Size 从 ViewController 调用自定义 UIView

标签 ios objective-c uiview call

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

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/

相关文章:

ios - NSMutableArray objectAtIndex

ios - FCNDEF消息查询NDEFStatusWithCompletionHandler :]: unrecognized selector sent to instance

iphone - 如何在动画时获取项目的坐标?

ios - 更改 UIView 的背景颜色

ios - 如何在 UIMenu 显示支持动态操作之前对其进行修改

android - 在默认网络浏览器中打开 URL

iphone - 如何以不同方式格式化 UILabel 字符串中的不同字符?

objective-c - 将 NSMenuItems 与 Actions 连接起来,反之亦然

objective-c - iOS 5.1 + PortraitMode 中的 UISplitViewController + MasterController 中的 UIActionSheet = 断言失败

ios - 使用 Swift 在子类中更改方向更改时更改自定义 View 的框架