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



Creating a custom UIView using a Nib
Assumptions
- You are familiar with creating UIView subclasses, and instantiating UIView’s both from a Nib file or in code
- 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.
- 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)
{
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.
{
[super viewDidLoad];
CustomView *customView = [CustomView customView];
[self.view addSubview:customView];
}
Code Explanation
- First we access the main bundle and load the nib we created.
- 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.
- 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
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的更多相关文章
- iOS Programming Subclassing UITableViewCell
iOS Programming Subclassing UITableViewCell 1.Creating BNRItemCell UITableViewCell is a UIView subc ...
- iOS Programming State Restoration 状态存储
iOS Programming State Restoration 状态存储 If iOS ever needs more memory and your application is in the ...
- iOS Programming Auto Layout: Programmatic Constraints 自动布局:通过编程限制
iOS Programming Auto Layout: Programmatic Constraints 1. However, if your views are created in co ...
- iOS Programming Introduction to Auto Layout 自动布局
iOS Programming Introduction to Auto Layout 自动布局 A single application that runs natively on both t ...
- iOS Programming Touch Events and UIResponder
iOS Programming Touch Events and UIResponder 1 Touch Events As a subclass of UIResponder, a UIView ...
- iOS Programming Camera 2
iOS Programming Camera 2 1.1 Creating BNRImageStore The image store will fetch and cache the image ...
- iOS Programming UINavigationController
iOS Programming UINavigationController the Settings application has multiple related screens of info ...
- iOS Programming Editing UITableView
iOS Programming Editing UITableView 1.1 Editing mode UITableView has an editing property, and when ...
- iOS programming UITabBarController
iOS programming UITabBarController 1.1 View controllers become more interesting when the user's acti ...
随机推荐
- JavaScript笔记——使用AJax
在使用过JQuery之后,再来看JavaScript的Ajax实现就会觉得很麻烦,不过,最近使用到了,就记录一下吧 在JavaScript中Ajax的实现可以分为四步: 第一步 得到XMLHttpRe ...
- enq:TM-contention
enq:TM-contention 2011-08-04 15:55:17 分类: Linux 7.1 enq:TM-contention 执行dml期间,为防止对与dml相关的对象进 ...
- 广义线性模型(Generalized Linear Models)
在线性回归问题中,我们假设,而在分类问题中,我们假设,它们都是广义线性模型的例子,而广义线性模型就是把自变量的线性预测函数当作因变量的估计值.很多模型都是基于广义线性模型的,例如,传统的线性回归模型, ...
- python查找文件相同的和包含汉字的
#!/usr/bin/env python # Version = 3.5.2 import os import time d_path = '/data/media' log_file = 'res ...
- ojective-c convert to pascal pattern
ojective-c convert to pascal pattern http://www.cnblogs.com/cnsoft/archive/2013/06/09/3128619.html C ...
- java之api讲解
1:数值运算 Java提供了java.lang.Math类支持数值运算 看文档 java.lang叫做核心语言包,里面包含的是Java中最基础的一些类,此包中的类,可以使用,不用import该包 举例 ...
- 转载--浅谈spring4泛型依赖注入
转载自某SDN-4O4NotFound Spring 4.0版本中更新了很多新功能,其中比较重要的一个就是对带泛型的Bean进行依赖注入的支持.Spring4的这个改动使得代码可以利用泛型进行进一步的 ...
- 去除winrar弹出购买许可证的提示
我们在使用winrar压缩包管理器时,经常会遇到弹出购买许可证的提示,影响了我们操作软件的友好性,接下来我们就来处理避免这种情况的再次发生.弹出购买许可证的图形如下: 处理方法如下: 新建一个记事本文 ...
- 微信小程序相关一、模仿京东静态登录页面
一.培训的第一天,基本上没有什么最新的东西,但是看到老师的代码收获的确实是不少. 1.1.首页代码很简洁,将共有的样式都提取的很好. 1.2.其次是每一个小块写样式的时候用到了好多子代选择器和后代选择 ...
- java算法 第七届 蓝桥杯B组(题+答案) 6.方格填数
6.方格填数 (结果填空) 如下的10个格子 (如果显示有问题,也可以参看[图1.jpg]) 填入0~9的数字.要求:连续的两个数字不能相邻.(左右.上下.对角都算相邻) 一共有多少种可能的填数方案 ...