【问题标题】:How to Call the Custom UIView from ViewController using Frame Size如何使用 Frame Size 从 ViewController 调用自定义 UIView
【发布时间】:2023-03-28 22:47:01
【问题描述】:

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

ViewController.m

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

LoginViewKarnataka(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]];
}
}

【问题讨论】:

    标签: ios objective-c uiview call


    【解决方案1】:

    将您的 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));
    

    【讨论】:

    • 如果我想通过这样做来打印视图的帧大小,这意味着它会显示错误 Property 'View' not found on object 'LoginViewKarnataka'。
    • 它没有显示LoginViewkarnatakausernameLabel。请检查并更新正确的解决方案兄弟。
    • 请查看我更新的答案。为了确认,我已将背景颜色作为红色添加到 karnatakView 。如果有任何问题,请发布屏幕截图。
    • 感谢它的工作。但旧的视图值消失了。我需要旧值。
    • 你必须改变 LoginViewKarnataka 的框架位置。此视图可能与您的控制器元素重叠。更改 LoginViewKarnataka 的“x”和“y”位置并尝试。这会帮助你
    【解决方案2】:

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

    [self addSubview:usernameLabel];
    

    附:如果您需要记录任何帧值,那么您可以简单地记录视图。框架值打印在视图的描述中。如果您创建了任何复杂的 UI,也可以使用DCIntrospect 进行 UI 调试。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多