ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 2
    COMP4126
    Progress0 / 38 topics
    Topics
    1. Creating an iOS App: Understanding Xcode2. Using the Xcode interface builder and objects library3. Understanding view hierarchy and creating a custom app icon4. Outlets, Actions, and Views: Understanding outlets and actions5. Using text fields, buttons, labels, web views, and page controllers6. Using views with subviews and creating views using code7. Using View Controllers: Working with the single view template8. Exploring the app delegate and adding new view controllers9. Transitioning between multiple view controllers using animations10. Application Templates: Tabbar and master detail templates11. The iOS Keyboard: Customizing for different inputs12. Adjusting text field behaviors and dismissing the keyboard13. Detecting keyboard activities with notification center14. Using scroll view and responding to keyboard activities programmatically15. Working with Different iOS Devices (iPhone & iPad): Detecting device hardware16. Dynamically adjusting graphical layouts and creating universal apps17. Using Table Views: Understanding UITableView and UITableViewCell18. Working with UITableView data source and delegate19. Master detail template, drill-down menus, and navigation20. Using property lists for data persistence and creating multi-section tables21. Supporting Screen Rotations: Portrait and landscape modes22. Handling device rotation and forcing specific orientation23. Dynamically adjusting layouts based on rotation24. Working with Databases: Importing sqlite3 and creating a database25. Writing tables, inserting records, and bundling a database with your app26. Checking for database existence and reading/displaying data27. Using Animations & Video: NSTimer class and object transformations28. Rotation, scaling, translation, animating image arrays, and playing video29. Accessing Integrated iOS Apps: Email, Safari, and SMS30. Working with camera and photo library31. Using Web Services: Consuming and parsing XML and JSON32. Integrating Twitter and Facebook with iOS apps33. Working with iOS Maps and Location Services: MapKit and MKMapView34. Getting and displaying user location and directional information35. Displaying map annotations, disclosure buttons, and reverse geocoding36. Working with iCloud37. Working with the Accelerometer: Gyroscope and accelerometer38. Outputting sensor data and using the Shake API
    COMP4126›Using views with subviews and creating views using code
    Mobile Application Development 2Topic 6 of 38

    Using views with subviews and creating views using code

    4 minread
    596words
    Beginnerlevel

    📱 Using Views with Subviews & Creating Views Using Code (iOS – Xcode)


    ✅ 1. Definition

    • View: A rectangular UI element displayed on screen (e.g., label, button).
    • Subview: A view that is placed inside another view (parent view).
    • Creating views using code: Instead of using storyboard, UI elements are created and configured programmatically in Swift.

    🧠 2. Key Concepts

    🔹 View Hierarchy

    • Views are arranged in a parent–child structure
    • Parent = Superview
    • Child = Subview

    🔹 Programmatic UI

    • UI is built using Swift code
    • No drag-and-drop needed
    • Gives more control and flexibility

    🔹 Frame vs Constraints

    Term Meaning
    Frame Position and size (x, y, width, height)
    Auto Layout Constraints for responsive design

    🏗️ 3. Using Views with Subviews


    🔹 Adding a Subview

    Syntax:

    parentView.addSubview(childView)
    

    🔹 Example

    let parentView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    parentView.backgroundColor = .lightGray
    
    let childView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200))
    childView.backgroundColor = .blue
    
    parentView.addSubview(childView)
    

    👉 Result:

    • Blue view appears inside gray view

    📊 Diagram Description (for Exams)

    Draw:

    • Large rectangle (Parent View)
    • Smaller rectangle inside it (Subview)
    • Label them clearly

    📌 Important Rules

    • Subview position is relative to parent view
    • Removing parent removes all subviews
    • Subviews are drawn on top of parent
    • Order matters (top view overlaps below views)

    ⚙️ 4. Creating Views Using Code


    🔹 Step 1: Import UIKit

    import UIKit
    

    🔹 Step 2: Create a View

    let myView = UIView()
    myView.backgroundColor = .red
    

    🔹 Step 3: Set Frame

    myView.frame = CGRect(x: 50, y: 100, width: 200, height: 100)
    

    🔹 Step 4: Add to Main View

    self.view.addSubview(myView)
    

    🧩 5. Creating UI Elements Programmatically


    🔹 Label Example

    let label = UILabel()
    label.text = "Hello World"
    label.frame = CGRect(x: 50, y: 100, width: 200, height: 50)
    
    self.view.addSubview(label)
    

    🔹 Button Example

    let button = UIButton(type: .system)
    button.setTitle("Click Me", for: .normal)
    button.frame = CGRect(x: 50, y: 200, width: 150, height: 50)
    
    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    
    self.view.addSubview(button)
    
    @objc func buttonTapped() {
        print("Button Pressed")
    }
    

    📐 6. Using Auto Layout in Code

    Instead of frame:

    myView.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        myView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        myView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        myView.widthAnchor.constraint(equalToConstant: 100),
        myView.heightAnchor.constraint(equalToConstant: 100)
    ])
    

    💡 7. Example

    🎯 Colored Box App

    • Create a red box inside main view
    • Add a label inside the box
    let box = UIView(frame: CGRect(x: 50, y: 100, width: 200, height: 200))
    box.backgroundColor = .red
    
    let label = UILabel(frame: CGRect(x: 20, y: 80, width: 160, height: 40))
    label.text = "Inside Box"
    label.textAlignment = .center
    
    box.addSubview(label)
    self.view.addSubview(box)
    

    ⚠️ 8. Common Mistakes

    • ❌ Forgetting to addSubview → view not visible
    • ❌ Wrong frame values → view off screen
    • ❌ Missing constraints → layout issues
    • ❌ Not setting translatesAutoresizingMaskIntoConstraints = false

    📝 9. Likely Exam Questions

    1. Define view and subview.
    2. Explain view hierarchy with example.
    3. How do you add a subview in iOS?
    4. Write code to create a UIView programmatically.
    5. Differentiate between frame and Auto Layout.
    6. Create a button using code and handle its action.
    7. Explain advantages of programmatic UI.
    8. Draw a diagram of view and subview relationship.

    📚 10. Quick Revision Summary

    • View = UI element

    • Subview = Child inside another view

    • Use addSubview() to attach views

    • UI can be created using:

      • Storyboard OR Code
    • Programmatic UI gives:

      • More control
      • Better customization
    • Use:

      • Frame → fixed layout
      • Auto Layout → responsive design

    Previous topic 5
    Using text fields, buttons, labels, web views, and page controllers
    Next topic 7
    Using View Controllers: Working with the single view template

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count596
      Code examples0
      DifficultyBeginner