Quantcast
Channel:
Viewing all articles
Browse latest Browse all 27

ios-creating-reusable-uiviews-with-storyboard – Part 2

$
0
0

This has is an updated version of ios-creating-reusable-uiviews-with-storyboard for Xcode 6.

TL:DR version:

  1. Create a new UIView subclass name it MyView.h/MyView.h
  2. Create a new XIB name it MyView.xib
  3. In MyView.xib select the File's Owner and set the class (using the right pane, third tab) to MyView
  4. Create an IBOutlet in MyView.h is of the type UIView*, call it contentView
  5. In InterfaceBuilder (with MyView.xib open) right-click drag the File's Owner the root view, and link it to contentView
  6. In MyView.m, override -awakeFromNib with the following:
    -(void)awakeFromNib {
        [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
     
        // The following is to make sure content view, extends out all the way to fill whatever our view size is even as our view's size is changed by autolayout
        [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self addSubview: self.contentView];
     
        [[self class] addEdgeConstraint:NSLayoutAttributeLeft superview:self subview:self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeRight superview:self subview:self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeTop superview:self subview:self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeBottom superview:self subview:self.contentView];
     
    }
     
    +(void)addEdgeConstraint:(NSLayoutAttribute)edge superview:(UIView *)superview subview:(UIView *)subview {
        [superview addConstraint:[NSLayoutConstraint constraintWithItem:subview
                                                              attribute:edge
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:superview
                                                              attribute:edge
                                                             multiplier:1
                                                               constant:0]];
    }

So that’s the first part, the second part is to create a UIView in some other XIB or storyboard, do whatever autolayout stuff you want with it and set it’s UIView class to “MyView”. When the XIB is loaded and displayed -it will show your view in there allowing you to customize views and reuse them.


Viewing all articles
Browse latest Browse all 27

Trending Articles