【问题标题】:iOS Bounds of UIView in ViewDidLoadViewDidLoad 中 UIView 的 iOS 边界
【发布时间】:2013-05-13 18:03:33
【问题描述】:

我想使用 UIView 的边界来创建 UILabel 并将其添加到 viewDidLoad 方法中的 UIView,但是,我发现 UIView 的边界在 viewDidLoad 中仍然为空。但是当我查看一个演示应用程序时,它的 UIView 的边界已经在 viewDidLoad 中初始化了。

在我有的界面

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIView *promotionView;
@end

我正在努力做

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *container = [[UIView alloc] initWithFrame:self.promotionView.bounds];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, container.bounds.size.height-100, 320, 20)];
    label.text = @"Promotion Title";
    [container addSubview:label];
    [self.promotionView addSubview: container];
}

但它不起作用,因为promotionView的边界为空。

【问题讨论】:

  • 将此代码更改为viewWillAppear 并检查插座是否已连接
  • promotionView 的边界不是nilpromotionView 本身就是 nil。确保您实际上将promotionView 设置为正确的视图。
  • @MidhunMP 将此类代码放在viewWillAppear 中是不合适的。 viewWillAppear 如果其他视图控制器从导航堆栈中被推送/弹出,则可以多次调用。
  • @rmaddy 我已经在情节提要中创建了 UIView 并将其链接到视图控制器,我还需要做什么吗?
  • viewDidLoad 中设置断点并使用调试器运行应用程序。到达断点时,检查promotionView 是否为nil

标签: ios null viewdidload bounds


【解决方案1】:

您可以在 viewDidAppear 中这样做:

-(void)viewDidAppear:(BOOL)animated {
    static int first = 1;
    if (first) {
        UIView *container = [[UIView alloc] initWithFrame:self.promotionView.bounds];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, container.bounds.size.height-100, 320, 20)];
        label.text = @"Promotion Title";
        [container addSubview:label];
        [self.promotionView addSubview: container];
        first = 0;
    }

}

【讨论】:

  • 谢谢,这解决了我的问题,但我仍然很好奇为什么我的 UIView 绑定在 viewDidLoad 中为 0 而演示代码可以使用它。我正在使用这里的演示代码 btw link
  • @doog,看起来他在那个演示中使用了 self.view.frame——控制器的 self.view 在 vi​​ewDidLoad 时不是 nil,但你添加的子视图是。
  • @doog,我应该在 viewDidLoad 中限定我关于子视图边界为 0 的评论——当自动布局打开时这是真的(默认情况下),但它会有你的边界如果关闭自动布局,则在情节提要中设置。我总是保持打开状态,然后使用约束而不是设置框架来调整视图大小。
猜你喜欢
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2011-05-08
  • 2010-11-10
  • 1970-01-01
相关资源
最近更新 更多