Creating Custom View in iOS Application

Dheeraj Kumar Gunti

Reading Time : ( words)


There will be certain design requirement where we need have a seperate view to be displayed on the view controller.

This example shows how to create a custom view and display it on a controller.

  • Create a Empty iOS Solution.
  • Add a View Contoller to the Solution.
  • Create few files which are indicated in the below images.








You can see three files created in the solution.

  • SampleView Class File
  • SampleView designer File
  • SampleView XIB File

Drag and drop designer.cs file to the class file so that it indicates those two are grouped together as below.




Open the SampleView.cs and Inherit the class from UIView.

Open the SampleView.designer.cs and specify Register attribute with the same name as class name. This indicates the compiler that it is a custom designer class.

[Register ("SampleView")]
public class SampleView
{
    public SampleView ()
    {
    }
}

Create a Nib object and Instantiate it.

public static readonly UINib Nib = UINib.FromName ("SampleView", NSBundle.MainBundle);
public static readonly NSString Key = new NSString ("SampleView");
public partial class SampleView : UIView
{
    public static readonly UINib Nib = UINib.FromName ("SampleView", NSBundle.MainBundle);
    public static readonly NSString Key = new NSString ("SampleView");
    public SampleView (IntPtr handle) : base (handle)
    {
    }
    public static SampleView Create ()
    {
    return (SampleView)Nib.Instantiate (null, null) [0];
    }
}

Build the solution. Open the .XIB file in XCode.

Make this View as freeform as below.




Choose the SampleView class from the class inspector.



Add a Control to the UIView and Create an Outlet to that Control. In this example I have used a UITextField.



[Register ("SampleView")]
partial class SampleView
{
    [Outlet]
    public UIKit.UILabel LblText { get; set; }
    void ReleaseDesignerOutlets ()
    {
    if (LblText != null) {
            LblText.Dispose ();
            LblText = null;
    }
    }
}

Open the View Controller and add the view as below.

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    var views = NSBundle.MainBundle.LoadNib ("SampleView", null, null);
    var contentCell = Runtime.GetNSObject (views.ValueAt (0)) as SampleView; 
    contentCell.Frame = new CGRect (10, 180, 300, 100);
    contentCell.LblText.Text = "This is Sample Custom View";
    this.View.Add (contentCell);
}

Output:



Enjoy Coding..... :)