Rendering Custom Views for Xcode Interface Builder .

Posted in: Blog

It is a normal practice to create custom components in an iOS application in order to reuse the code for multiple files.

Earlier, custom components were implemented using code files instead of Interface Builder. It was a hectic approach as all of the subviews were being created during runtime. It also required regressive testing to examine if the subviews were perfectly placed or needed more code for drawing sublayers using drawRect method.

To overcome this problem, our Appdev360 engineer Asif Iqbal tried using XIB file attached to Custom Class. It became easier to design custom components as he got an idea of sub viewing the application during runtime. Although this approach fulfilled the requirements, he needed Interface Builder to render Custom View while using the View Controller.

With the launch of Xcode 6, Apple introduced “View That Render in Interface Builder”. Asif used this function in order to make a smooth transition. For that, he took the following steps:

  • Created a Custom View Class and it’s XIB file. Say, @IBDesignable class CustomView: UIView
  • Designed the related XIB file and implemented other functional aspects
  • Override the method “prepareForInterfaceBuilder” for rendering View in Interface Builder
    override func prepareForInterfaceBuilder() {
     super.prepareForInterfaceBuilder()
        // Paste your code here to render in Interface Builder.
        // e.g. Adding Subviews using addSubview(). Set layer properties using layer.borderColor
    }
  • Following functionality can also be achieved by overriding drawRect method
    override func drawRect(rect: CGRect) {
                            
           // get the current drawing context
           let context = UIGraphicsGetCurrentContext()
                    
           // set the line color and width
           CGContextSetStrokeColorWithColor(context, borderColor.CGColor)
           CGContextSetLineWidth(context, borderWidth)
                    
           // start a new Path
           CGContextBeginPath(context)
                    
           CGContextMoveToPoint(context!, startPoint.x, startPoint.y)
           CGContextAddLineToPoint(context!, endPoint.x, endPoint.y)
           // close and stroke (draw) it
           CGContextClosePath(context)
           CGContextStrokePath(context)
                    
            
        }
  • Dragged & Dropped View from Object Library to the View Controller’s View
  • Applied the appropriate constraints
  • Changed the Class name to “My Custom View”

As a result, whatever code he inserted in the “prepareForInterfaceBuilder” appeared in Interface Builder.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *