【问题标题】:iOS Layout custom view create with xib when resized调整大小时使用 xib 创建 iOS Layout 自定义视图
【发布时间】:2015-01-22 09:35:07
【问题描述】:

我创建了有两个标签的 MyCustomView。一个在左边,一个右对齐和在右边。它有大约 30px 的高度(这并不重要)。我将它连接到 xib 并且它可以工作。在 .xib 中,我将主视图宽度设置为 400px 并为标签设置自动布局约束。

现在的问题。当我使用 UIView 添加到 IB 中的控制器并将类设置为 MyCustomView 时,我看到左标签但右标签不在屏幕上。我设置了正确的约束,但它不起作用。当我尝试通过鼠标在 .xib 中调整 MyCustomView 的大小并使用边缘移动时,这没关系,但是当我在右列中“手动”设置宽度值时,它的布局不正确(它根本不会改变)。问题出在哪里?我该如何解决这个问题?

@implementation MyCustomView

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    self.backgroundColor = [UIColor clearColor];

    self.view = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomView"
                                               owner:self
                                             options:nil] firstObject];

    [self addSubview:self.view];
    //self.translatesAutoresizingMaskIntoConstraints = NO;
}

- (void)awakeFromNib {
    [super awakeFromNib];

    //[self setNeedsUpdateConstraints];
    //[self setNeedsLayout];
}

@end

正如您在 cmets 中看到的,我尝试了一些方法,但没有任何帮助。

【问题讨论】:

  • 你说你已经为标签设置了自动布局约束,你能简单解释一下你做了什么吗?
  • 对于右标签,我设置了约束:宽度为 100,顶部、底部和尾随空间为 0。
  • 在将自定义视图添加到您的超级视图后,您不应该将约束添加到您的自定义视图本身吗?
  • 我对您在此处的设置感到有些困惑。 MyCustomView 有对应的XIB,对吧?如果是这样,您为什么要在 commonInit 中手动加载 XIB?如果 MyCustomView 是 UIView,self.view 引用什么?

标签: ios objective-c autolayout custom-controls constraints


【解决方案1】:
  1. 新文件 --> iOS (Source) -- Cocoa Touch --> 下一个

  2. 输入姓名

  3. 在 MyCustomView.m 中添加代码

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.view.backgroundColor = [UIColor redColor];
        self.preferredContentSize = CGSizeMake(30.0, 400.0);
    }
    return self;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 2011-12-30
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多