Ticker

6/recent/ticker-posts

Programatically creating UIView in iOS || Swift

UIView

UIView is a rectangular area on mobile device screen, and the interface to managing the content in that area. At run time, a view object renders the content in that area and also handles the interactions with that content.

UIView object is the main responsible to handle all the user interface and also it is responsible to handle the following interaction

  • Drawing and Animations

  1. Views draw content in their rectangular area using technologies such as UIKit, Core Graphics and OpenGL ES.
  2. And also it has some basic properties to animate the UIView from it's original values.

frame
bounds
center
transform
alpha
backgroundColor
contentStretch

    • Layout and Sub-view management
    1. A UIView may containts 0 or more subview
    • Event handling
    1. A UIView can response to the user interactions also by adding gestures to view object
    Now let's create new xcode project to understand these things clearly. To create new xcode project open Xcode/New/Project/iOS/Appllication/Single view application.
    Name your project and choose language as swift.

    Let's go into coding part,

                    


    // 1) allocating and initilizing UIView object and adding it to ViewController's main container view
            let redView = UIView(frame: CGRect(x:20,y:50,width:self.view.frame.width-40,height:self.view.frame.height-50))
            self.view.addSubview(redView)
            
            // 2) specifies the view backgrount color by UIColor object
            redView.backgroundColor = UIColor.red
            
            
            // 3) handle layer properties of view object
            redView.layer.cornerRadius = 10
            redView.layer.masksToBounds = true
            redView.layer.borderColor = UIColor.green.cgColor
            redView.layer.borderWidth = 5
            
            // 4) animating uiview object
            let scaleAnimate:CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
            scaleAnimate.fromValue = 0
            scaleAnimate.toValue = 1
            scaleAnimate.duration = 5;
            scaleAnimate.repeatCount = 5
            scaleAnimate.autoreverses = true
            scaleAnimate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
            redView.layer.add(scaleAnimate, forKey: "scaleNormalAnimation")
            
            
            //adding another view to the reView as it's sub-view
            let yellowView = UIView(frame: CGRect(x:10,y:10,width:redView.frame.width-20,height:redView.frame.height-20))
            redView.addSubview(yellowView)
            yellowView.backgroundColor = UIColor.yellow



    Download demo code from here.


    Post a Comment

    0 Comments