Libor Zapletal
Libor Zapletal

Reputation: 14102

iOS Layout custom view create with xib when resized

I created MyCustomView which has two labels. One at left and one with right align and at right. It has about 30px height (it's not important). I connect it to xib and it works. In .xib I set main view width to 400px and set autolayout constraints for labels.

Now the problem. When I added to my controller in IB with UIView and set class to MyCustomView I see left label but right label is out of screen. I set constraints right but It doesn't work. When I tried to resize MyCustomView in .xib by mouse and moving with edges it's okay but when I set width value "manually" in right column it doesn't layout right (it doesn't change at all). Where is the problem? How can I fix this?

@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

As you can see in comments I tried some ways but nothing helped.

Upvotes: 2

Views: 384

Answers (1)

ArNo
ArNo

Reputation: 2648

  1. New File --> iOS (Source) -- Cocoa Touch --> Next New File

  2. Enter Name MyCustomView

  3. Add code in 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;
}

Upvotes: 1

Related Questions