Wednesday, 6 July 2011

How to make a custom view in iPhone application?

This post deals with making custom views in iPhone application. You can design your views according to your ideas rather than using plain UIView. You can draw variety of patterns in your custom views using Quartz framework and then use these views in your application.

In this snippet we will add a simple coloured rectangle in a view.

1) Add a new file in your project and select it as a subclass of UIView as shown in figure.


2) Lets name it as “new”, so now you must have got two files “new.h” and “new.m” . new.h inherits UIView.

3) Lets say we have a view controller. Open its xib file, select view in file owner window and change its class from UIView to new in library inspector window as shown in figure.



4) Now come to new.m file, uncomment and ovewrite its “drawRect:” method with code shown below

- (void)drawRect:(CGRect)rect {
    // Drawing code.
 CGContextRef context = UIGraphicsGetCurrentContext();
 CGContextSetRGBStrokeColor(context, 1.0f, 0.3f, 0.5f, 1.0f);
 CGContextStrokeRectWithWidth(context,CGRectMake(20, 20, 280, 420), 10);
}

5) Save, build and run the project.

6) Output is as shown below. Now you can use this view in any view controller in your application.



No comments:

Post a Comment