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!

COMMENTS

    1. Mihai Damian says:

      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.

      • Mike Turner says:

        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.

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

  1. iOS Programming Subclassing UITableViewCell

    iOS Programming Subclassing UITableViewCell  1.Creating BNRItemCell UITableViewCell is a UIView subc ...

  2. iOS Programming State Restoration 状态存储

    iOS Programming State Restoration 状态存储 If iOS ever needs more memory and your application is in the ...

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

    iOS Programming  Auto Layout: Programmatic Constraints  1.  However, if your views are created in co ...

  4. iOS Programming Introduction to Auto Layout 自动布局

    iOS Programming Introduction to Auto Layout   自动布局 A single application that runs natively on both t ...

  5. iOS Programming Touch Events and UIResponder

    iOS Programming Touch Events and UIResponder  1 Touch Events  As a subclass of UIResponder, a UIView ...

  6. iOS Programming Camera 2

    iOS Programming Camera  2  1.1 Creating BNRImageStore The image store will fetch and cache the image ...

  7. iOS Programming UINavigationController

    iOS Programming UINavigationController the Settings application has multiple related screens of info ...

  8. iOS Programming Editing UITableView

    iOS Programming Editing UITableView 1.1 Editing mode  UITableView has an editing property, and when ...

  9. iOS programming UITabBarController

    iOS programming UITabBarController 1.1 View controllers become more interesting when the user's acti ...

随机推荐

  1. bbbbb

  2. OD 实验(十二) - 对一个 Delphi 程序的逆向

    程序: 运行程序 界面显示的是未注册 点击 Help -> About 点击 Use Reg Key 这里输入注册码 用 PEiD 看一下 该程序是用 Delphi 6.0 - 7.0 写的 逆 ...

  3. IDA Pro 权威指南学习笔记(十一) - 名称与命名

    多数情况下,要修改一个名称,只需单击想要修改的名称(使其突出显示),并使用快捷键 N 打开更名对话框 右击需要修改的名称,并在出现的上下文菜单中选择 Rename 选项,也可以更改名称 参数和局部变量 ...

  4. mongodb分片(七)

    1.插入负载技术分片架构图 2.片键的概念和用处 看下面这个普通的集合和分片后的结果 3.什么时候用到分片呢? 3.1机器的磁盘空间不足 3.2单个的mongoDB服务器已经不能满足大量的插入操作 3 ...

  5. 【296】Python 默认 IDE 修改

    参考:找回Python IDLE Shell里的历史命令(用上下键翻历史命令怎么不好用了呢?) 参考:Python IDLE快捷键一览 参考:Python IDLE 自动提示功能 参考:如何让pyth ...

  6. win 10+ iis 10 部署.net core 1.1 web api

    今天上午部署了wcf,部署了好久,一直没有部署好,最后找到了dudu的部署方法,结果中午吃饭的时候成功了,这是链接:http://www.cnblogs.com/dudu/p/3328066.html ...

  7. shell 脚本的坑

    最近都在写shell脚本,免不了遇到每个新手都要填的坑,在这里简单记录一下. test语句的坑 test语句在shell脚本里用的非常多,像if语句后面的其实都是test语句,也是新手最容易遇到坑的地 ...

  8. NSTimer类的使用

    转载于:http://www.cnblogs.com/wujian1360/archive/2011/09/05/2167992.html 创建一个 Timer + scheduledTimerWit ...

  9. Linux运维基础入门(三):网络基础知识梳理03

    一,ARP协议 使用ARP协议可以查出擅自更改IP地址主机的MAC地址.在学习ARP协议前需要了解广播和广播域的相关概念. 1.1 广播与广播域 在超市找人时,如果不知道对方的位置就需要到服务台通过广 ...

  10. Linux实战教学笔记34:企业级监控Nagios实践(上)

    一,Nagios监控简介 生活中大家应该对监控已司空见惯了,例如:餐馆门前的监控探头,小区里的视频监控,城市道路告诉监控探头等,这些监控的目的大家都很清楚,无须多说.那么,企业工作中为什么要部署监控系 ...