Xib Custom View in iOS for use in storyboard

Source: Internet
Author: User

1, create UIView subclass named MyView

2, New a xib named MyView

P1

3, configuring The properties of the xib

P2

4. Add a background color to the View, add a button and customize the button constraint, where I add a vertical center, buttonand View width, button to the left of thestart position is 0.

P3

5, set file ' s owner = MyView in Xib, drag view to the associated code named Contentview

P4

6, Add a view to Viewcontroller in storyboard , then set the view class to MyView

Add code in 7,myview.m

-(void) awakefromnib{    NSLog (@ "awake from nib");    [[NSBundle Mainbundle] loadnibnamed: @" MyView " owner:self Options:nil];    [Self AddSubview:self.contentView];}

You can see the view after this execution , but there is a serious problem, that is, MyView does not do AutoLayout when it is displayed . It is only shown in the size of the xib, and in practice it may be expected that the custom view inside the Viewcontroller can also automatically match the size.

For the above problem, my workaround is to override the Setframe method, as follows:

8, Add code in myview.m

-(void) Setframe: (cgrect) frame{    [Super Setframe:frame];     = frame;     0 ;     0 ;      = rect;}

drag MyView iboutlet to Viewcontroller in StoryBoard

P5

Add code in viewdidload

[Self.myview SetFrame:self.myView.frame];

If your custom view is released on top of Tableviewcell:

In this case, write in the Tableviewcell code:

// If there are dimensions and the like to write in the method -(void) layoutsubviews {    [super layoutsubviews]    ; // adapting the dimensions in a custom view to the constraints in SB       [Self.myview setFrame:self.myView.frame];}

This allows the constraints set in the StoryBoard to correctly affect the MyView.

Xib Custom View in iOS for use in storyboard

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.