iOS Programming Recipe 6: Creating a custom UIView using a Nib

iOS Programming Recipe 6: Creating a custom UIView using
a Nib

JANUARY
7, 2013 BY MIKETT 12
COMMENTS

Creating a custom UIView using a Nib


Assumptions

  1. You are familiar with creating UIView subclasses, and instantiating
    UIView’s both from a Nib file or in code

  2. You are familiar with Nib files

Background

Sometimes you find yourself trying to create a quick composite UIView (UIView
subclass w/ multiple subviews) where a UIViewController doesn’t seem
necessary Please note that a UIViewController is the right choice
most of the time
. This can be a real pain to setup entirely in code if
you have many subviews, and god forbid if you want to use auto layout! So you
may find yourself wanting to use a nib to simplify things a bit, well this
tutorial will go through the process of doing just that.

Getting Started

  • Create a new Xcode project based on the single view application template
    for iOS. This tutorial will assume you are using ARC, so you may want to make
    that selection when creating the new project.

  • Once you have created the new project a new UIView subclass to the project
    and name itCustomView.

  • Then create a new Nib file
    named CustomView.nib and add it to the
    project.

Setup the UIView Subclass (using a nib)

  • Open the newly created nib and add a UIView to it.

  • In the Attributes Inspector under
    the Simulated
    Metrics
     section, click the size drop-down
    menu and select none, this will allow you to resize the
    UIView to whatever size you like.

  • Resize the view to something like 200×300.

  • With the newly added UIView selected open the Identity
    Inspector
     and change the classname
    to CustomView matching the one you previously
    created.

  • Add a UILabel as a subview of the view and change the title
    to My Custom View. Then center it in the view, it should
    resemble the one shown below.

Creating a Convenience Initializer

Next we will create a convenience initializer in the CustomView class that
will load the CustomView from the nib instead of creating it in code

    • Open CustomView.h and add the following class
      method definition.

+ (id)customView;

    • Next open CustomView.m and implement the
      class method as shown below (Please keep in mind this is a very basic
      implementation for our basic UIView subclass, you can alter it to your
      liking)

+ (id)customView
{
   
CustomView *customView = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:nil options:nil] lastObject];

 
  // make sure customView is not nil or the wrong
class!
    if ([customView isKindOfClass:[CustomView class]])
        return customView;
    else
 
      return nil;
}

Finishing The Demo App

    • Open ViewController.m and add the
      following viewDidLoad method, this will use our
      convenience initializer to create a CustomView and then we add it to our
      view hierarchy. You will also need to import CustomView.h in
      ViewController.m.

- (void)viewDidLoad
{
 
  [super viewDidLoad];

    CustomView *customView = [CustomView
customView];
    [self.view addSubview:customView];
}

Code Explanation

      1. First we access the main bundle and load the nib we created.

      2. loadNibNamed:owner:options: returns an NSArray
        containing each of the top level objects in the nib. Since in our case we
        know there should only be one top level object (CustomView as we specified
        earlier) we can then call lastObject on the
        array. lastObjectis used in order to safely access
        the array in
        case loadNibNamed:owner:options: failed. Note
        that lastObject returns nil if the array is
        empty.

      3. Finally we ensure that customView is
        actually a “CustomView” not some other class or nil.

That’s It!

As always if you have any suggestions for future recipes, or any questions or
comments, please let us know!

FILED UNDER: INTERMEDIATEIOS
6
RECIPES TAGGED
WITH: INTERFACE BUILDERIOS 6IOS DEVELOPMENTIOS PROGRAMMING,NIBOBJECTIVE-CUIVIEW

COMMENTS


    1. Mihai Damian says:

      January
      9, 2013 at 3:11 pm

      One potential drawback with of approach is that you cannot directly link
      IBOutlets from the Nib since you have no file owner for it. Of course you
      could grab the subviews by tags and assign them yourself but this is error
      prone since it’s much more difficult to keep track of tags. Alternatively
      you could create an extra “template” instance of CustomView, set it as the
      file owner and then do the manual IBOutlet assignment from the template
      instance to the actual instance that you’ll be returning. This has the
      advantage of explicitly naming the UIViews you’re working with but it feels
      a bit hackish and it takes the most effort to implement.

      Reply

      • Mike Turner says:

        January
        9, 2013 at 5:07 pm

        Thanks for the comment!

        You can actually link up IBActions & IBOutlets, although it is
        slightly different than with a UIViewController. Using the example above
        add this property declaration to CustomView.h.

        //This will link to the
        label in CustomView.xib
         @property (nonatomic,
        strong) IBOutlet UILabel *label;

        Now in CustomView.xib, (control + drag) from the top level object (our
        CustomView object, where the property declaration lives, instead of file’s
        owner) to the UILabel. You should be presented with a HUD allowing you to
        select the “label” outlet just created!

        I’ll append the post to show this process.

        Reply

iOS Programming Recipe 6: Creating a custom UIView using a
Nib,码迷,mamicode.com

iOS Programming Recipe 6: Creating a custom UIView using a
Nib

时间: 2024-10-16 13:50:43

iOS Programming Recipe 6: Creating a custom UIView using a Nib的相关文章

iOS Programming Subclassing UITableViewCell

iOS Programming Subclassing UITableViewCell? 1.Creating BNRItemCell UITableViewCell is a UIView subclass. UITableViewCell是UIView的子类. When subclassing UIView (or any of its subclasses), you often override its drawRect: method to customize the view's a

iOS Programming Views :Redrawing and UIScrollView

iOS Programming Views :Redrawing and UIScrollView? 1.1 event? You are going to see how views are redrawn in response to an event. 你将看到view如何响应event的. You declared properties in header files. You can also declare properties in class extensions. 你可以声明属

iOS Programming State Restoration 状态存储

iOS Programming State Restoration?状态存储 If iOS ever needs more memory and your application is in the background, Apple might kill it to return memory to the system. 如果iOS 需要更多的memory,你的应用在后台,apple 可能杀死它来得到更多的内存给系统. This should be transparent to your u

iOS Programming Introduction to Auto Layout 自动布局

iOS Programming Introduction to Auto Layout ? 自动布局 A single application that runs natively on both the iPad and the iPhone is called a universal application. 一个原生的能运行在iPad 和iPhone 的应用叫做universal application? Then select the Homepwner target in the pr

iOS Programming View Controllers 视图控制器

iOS Programming View Controllers? 视图控制器? 1.1? A view controller is an instance of a subclass of UIViewController. 一个view controller 是一个UIViewController的子类. A view controller manages a view hierarchy. 一个view controller 管理一个视图树. It is responsible for c

iOS Programming Auto Layout: Programmatic Constraints 自动布局:通过编程限制

iOS Programming? Auto Layout: Programmatic Constraints? 1.? However, if your views are created in code, then you will need to constrain them programmatically. 如果你的view是由代码创建的,那么你需要用编程限制它了. To have a view to work with, you are going to recreate the im

iOS Programming Touch Events and UIResponder

iOS Programming Touch Events and UIResponder? 1 Touch Events? As a subclass of UIResponder, a UIView can override four methods to handle the four distinct touch events: 作为UIResponder的一个子类,UIView可以重写四个方法来处理touch events. (1) a finger or fingers touches

iOS programming UITableView and UITableViewController

iOS programming? UITableView and UITableViewController A UITableView displays a single column of data with a variable number of rows. UITableView 展示单列数据和不定数量的行. ? ?Create a new iOS Empty Application project and configure it 1.1 UITableViewController

iOS Programming UISplitViewController

iOS Programming UISplitViewController? The iPad, on the other hand, has plenty of screen space to present both views using a built-in class called UISplitViewController. iPad 有足够的屏幕空间来展现两个view用built-in 类称为UISplitViewController. UISplitViewController