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 6RECIPES 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

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/p/3700509.html

时间: 2024-08-03 09:20:16

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

iOS Programming 触摸事件处理详解

iphone/ipad无键盘的设计是为屏幕争取更多的显示空间,大屏幕在观看图片.文字.视频等方面为用户带来了更好的用户体验.而触摸屏幕是iOS设备接受用户输入的主要方式,包括单击.双击.拨动以及多点触摸等,这些操作都会产生触摸事件. 在Cocoa中,代表触摸对象的类是UITouch.当用户触摸屏幕后,就会产生相应的事件,所有相关的UITouch对象都被包装在事件中,被程序交由特定的对象来处理.UITouch对象直接包括触摸的详细信息. UITouch类中包含5个属性: window:触摸产生时所

iOS Programming - Views(视图 - 基本绘制,变换,平移,旋转,反转,倾斜)

1. Views A view (an object whose class is UIView or a subclass of UIView) knows how to draw itself into a rectangular area of the interface. Your app has a visible interface thanks to views. (eg: you can drag an interface widget, such as a UIButton,

iOS 各版本中的新特性(What's New in iOS)- 目录翻译完成

iOS 各版本中的新特性(What's New in iOS) 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 介绍 Introduction文档组织结构 Organization of Thi

iOS 基础类解析 - NSCharacterSet

iOS 基础类解析 - NSCharacterSet 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. NSCharacterSet Class Reference Inherits from N

DPC:Creating a DataBound List of Radio Buttons--PART2[等级:中]

In Part 1 we looked at how to bind a DataReader to a radio button list, but how do we respond to the user's choice? In this part we'll look at how to display a list of books for the particular publisher the user selected from the databound radio butt

IOS如何使用Instruments

How to Use Instruments in Xcode  Matt Galloway on December 5, 2012 Tweet This is a blog post by iOS Tutorial Team member Matt Galloway, founder of SwipeStack, a mobile development team based in London, UK. You can also find me on Google+. Learn how t

[ISUX译]iOS 9人机界面指南(三):iOS 技术

[ISUX译]iOS 9人机界面指南(三):iOS 技术 UI规范 summer 2015-11-29 3247浏览 0评论 专为0基础小白量身打造的UI设计入门课程(ps,ai软件+图标技巧),在线学习2个月包教会(公开课3位师傅),拜师费1500,随到随学,可插班.抢名额请加qq群:429369013咨询. 本文译自苹果官方人机界面指南 iOS Human Interface Guidelines ,由腾讯ISUX设计师翻译整理,非发文者一人之作. 文章索引 3.1 3D触摸(3D Touc

iOS 基础类解析 - NSDate

iOS 基础类解析 - NSDate 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. NSDate Class Reference Inherits from NSObject Conforms

iOS 8带来第三方输入法开放

摘要: 开放在苹果WWDC2014大会上被提到了很多次,围绕这个概念,iOS 8带来最振奋人心的特性莫过于用户呼吁已久的第三方输入法开放~而讯飞智能语音输入法就是基于iOS系统的首个第三方输入 "开放"在苹果WWDC2014大会上被提到了很多次,围绕这个概念,iOS 8带来最振奋人心的特性莫过于用户呼吁已久的第三方输入法开放~而讯飞智能语音输入法就是基于iOS系统的首个第三方输入法. 在功能上,讯飞暂时没有为iPhone带来太多额外创新的东西:支持普通话.粤语.英语和部分其他方言语音输