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. JS-用法

    JavaScript 用法 HTML 中的脚本必须位于 <script> 与 </script> 标签之间. 脚本可被放置在 HTML 页面的 <body> 和 & ...

  2. SSH框架搭建和整合(struts2、spring4、hibernate5)

    声明: 本博文是个人通过对ssh框架的学习.理解还有一些看法而描述出来的,可能有不足之处,请大家谅解,但希望能帮助到大家! 目的: 使初学者能更好的去了解SSH框架. 给以后的自己,也给别人一个参考. ...

  3. sql server xml 截断

    c#读取 sql生成的xml时,发生阶段. 加,type 解决

  4. HTTP头的Expires与Cache-control区别

    2010年3月24日 a18ccms 发表评论 阅读评论 今天在群里聊天.说道了Expires.这里来说明下这两个的区别吧. 1.概念 Cache-control 用于控制HTTP缓存(在HTTP/1 ...

  5. 16_Java正则和日期对象

    01正则表达式的概念和作用 * A: 正则表达式的概念和作用 * a: 正则表达式的概述 * 正则表达式也是一个字符串,用来定义匹配规则,在Pattern类中有简单的规则定义. 可以结合字符串类的方法 ...

  6. 异步编程之co——源码分析

    异步编程系列教程: (翻译)异步编程之Promise(1)--初见魅力 异步编程之Promise(2):探究原理 异步编程之Promise(3):拓展进阶 异步编程之Generator(1)--领略魅 ...

  7. ansible初识二

    一.ansible模块(yum.pip.service.conr.user.group) 上篇中我们已经学了ansible 的几个模块, 接下来再来学习几个, 那么你是否知道ansible 一共有多少 ...

  8. rabbitMQ消息队列1

    rabbitmq 消息队列 解耦 异步 优点:解决排队问题 缺点: 不能保证任务被及时的执行 应用场景:去哪儿, 同步 优点:保证任务被及时的执行 缺点:排队问题 大并发 Web nginx 1000 ...

  9. 搞点事情,使用node搭建反向代理

    导语 最近有个需求,需要对业务管理后台的操作记录进行上报.一般这种上报需求都是又后台同学来做比较合适的.但是因为后台人力的原因.这个工作落到了我这个小前端的头上.这里记录下做这个需求踩的一些坑. 一. ...

  10. vue打包静态资源路径不正确的解决办法

    vue打包静态资源路径不正确的解决办法 vue项目完成打包上线的时候会碰到静态资源找不到的问题,常见的有两个 1.js,css路径不对 解决办法:打开config/index.js,将其中的asset ...