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›Detecting keyboard activities with notification center
    Mobile Application Development 2Topic 13 of 38

    Detecting keyboard activities with notification center

    3 minread
    573words
    Beginnerlevel

    📱 Detecting Keyboard Activities with Notification Center (iOS – Xcode)


    ✅ 1. Definition

    The Notification Center in iOS is a system that allows apps to observe (listen to) events happening in the system or app, such as keyboard appearance and disappearance.

    👉 In simple terms: It lets your app know when the keyboard shows, hides, or changes size.


    🧠 2. Key Concepts

    🔹 NotificationCenter

    • A built-in iOS system class
    • Sends and receives event notifications

    🔹 Keyboard Notifications

    iOS provides predefined notifications for keyboard events:

    Notification Meaning
    keyboardWillShow Keyboard is about to appear
    keyboardDidShow Keyboard has appeared
    keyboardWillHide Keyboard is about to disappear
    keyboardDidHide Keyboard has disappeared
    keyboardWillChangeFrame Keyboard size/position changing

    🔹 Observer

    • A listener that waits for notifications
    • Your ViewController acts as an observer

    ⚙️ 3. How Notification Center Works

    Keyboard Event → Notification Center → Observer (ViewController) → Action
    

    🏗️ 4. Detecting Keyboard Events (Step-by-Step)


    🔹 Step 1: Add Observers

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self,
            selector: #selector(keyboardWillShow),
            name: UIResponder.keyboardWillShowNotification,
            object: nil)
        
        NotificationCenter.default.addObserver(self,
            selector: #selector(keyboardWillHide),
            name: UIResponder.keyboardWillHideNotification,
            object: nil)
    }
    

    🔹 Step 2: Handle Keyboard Appearing

    @objc func keyboardWillShow(notification: Notification) {
        print("Keyboard is shown")
    }
    

    🔹 Step 3: Handle Keyboard Hiding

    @objc func keyboardWillHide(notification: Notification) {
        print("Keyboard is hidden")
    }
    

    📏 5. Getting Keyboard Size (Important)

    Sometimes we need keyboard height to adjust UI.

    @objc func keyboardWillShow(notification: Notification) {
        if let userInfo = notification.userInfo,
           let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
            
            let keyboardHeight = keyboardFrame.height
            print("Keyboard height: \(keyboardHeight)")
        }
    }
    

    📊 6. Diagram Description (for Exams)

    Draw:

    Keyboard Appears
          ↓
    NotificationCenter sends event
          ↓
    ViewController receives notification
          ↓
    Adjust UI / Move TextField
    

    💡 7. Real Use Case Example

    🎯 Chat App

    Problem:

    • Keyboard covers text field

    Solution:

    • Detect keyboard height
    • Move input field upward
    @objc func keyboardWillShow(notification: Notification) {
        if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
            self.view.frame.origin.y = -keyboardFrame.height / 2
        }
    }
    
    @objc func keyboardWillHide(notification: Notification) {
        self.view.frame.origin.y = 0
    }
    

    🧹 8. Removing Observers (Important Rule)

    Always remove observers to avoid memory issues:

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    

    📌 9. Important Rules / Tips

    • Always register observers in viewDidLoad()
    • Remove observers in deinit
    • Use keyboard height to adjust UI layout
    • Handle both show and hide events
    • Avoid hardcoding UI shifts

    ⚠️ 10. Common Mistakes

    • ❌ Not removing observers → memory leaks
    • ❌ Ignoring keyboard height
    • ❌ UI not adjusting properly → text fields hidden
    • ❌ Using fixed values instead of dynamic keyboard size

    🧠 11. Best Practices

    • Use Auto Layout instead of manual frame shifting when possible
    • Animate UI changes with keyboard
    • Handle different device sizes
    • Use keyboard notifications for responsive design

    📝 12. Likely Exam Questions

    1. What is Notification Center in iOS?
    2. How do you detect keyboard appearance?
    3. List keyboard-related notifications.
    4. Write code to detect keyboard show event.
    5. Why is keyboard height important?
    6. Explain how to adjust UI when keyboard appears.
    7. What is the role of observers?
    8. Why should observers be removed?

    📚 13. Quick Revision Summary

    • Notification Center detects system events

    • Used for keyboard tracking in apps

    • Key notifications:

      • Show
      • Hide
      • Frame change
    • Steps:

      1. Add observer
      2. Handle event
      3. Adjust UI
      4. Remove observer
    • Used in chat apps, forms, login screens


    Previous topic 12
    Adjusting text field behaviors and dismissing the keyboard
    Next topic 14
    Using scroll view and responding to keyboard activities programmatically

    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 time3 min
      Word count573
      Code examples0
      DifficultyBeginner