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.

How to display a custom view instead of standard keyboard when the textfield becomes first responder?

This snippet deals with how to display custom view instead of keyboard when the textfield becomes first responder…

 

Write the highlighted code, as shown below, in .h file

Now come to .m file and write the code give below

@synthesize field;

Inside viewDidLoad method write the following code

UIImage *image=[UIImage imageNamed:@"apple-logo.jpg"];
	UIImageView *view=[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100, 200.0f)];
	[view setImage:image];

	field.inputView=view;

Here apple-logo.jpg is the image in the resource folder

 

Now come to .xib

Add a textfield and a label as shown below. Also make the connection

Now when you interact with textfield you will get your own view instead of keyboard

How to add a simple UIButton in a UIView by coding?


This post deals with adding a button in UIView by coding…

Create a button

 

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

button1.frame = CGRectMake(x, y, width, height);

where x and y are coordinates

width is width of the button,height is height of the button

[button1 setTitle:@"Hello" forState:UIControlStateNormal];

 

Add the button to parent view

[[self view] addSubview:button1];