Working with UIView, UILabel, UIButton, and UITextField in iOS
Course: iOS App Development Training
Topic: Working with UIView, UILabel, UIButton, and UITextField
Course Link: iOS App Development Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to UIKit Interface Components
UIKit is Apple's framework for building user interfaces in native iOS applications. It provides reusable components that developers use to display information, accept user input, respond to interactions, and organize screen layouts.
Four fundamental UIKit components are UIView, UILabel, UIButton, and UITextField. They are commonly used together to create login forms, registration screens, profile pages, search interfaces, settings screens, and many other application features.
UIView is the base class for many interface elements and is used to create containers and custom visual areas. UILabel displays text, UIButton responds to taps, and UITextField allows users to enter and edit text.
2. Learning Objectives
- Understand UIKit and its view hierarchy.
- Learn the purpose and features of UIView.
- Display text using UILabel.
- Create interactive controls using UIButton.
- Accept and validate user input using UITextField.
- Configure interface components using Swift.
- Understand Auto Layout and programmatic interface construction.
- Connect interface components using IBOutlet and IBAction.
- Handle user interactions and common interface errors.
- Build a practical form using the four components.
3. Understanding UIView
3.1 What Is UIView?
UIView is the fundamental building block of UIKit interfaces. It represents a rectangular area on the screen and can display content, contain other views, receive touch events, and participate in layout.
Many familiar UIKit components inherit from UIView, including UILabel, UIButton, and UITextField. This shared inheritance means they support many common properties, such as background color, transparency, dimensions, and layout behavior.
3.2 Common Uses of UIView
- Creating containers for related interface elements.
- Grouping labels, buttons, and text fields into sections.
- Adding background colors, borders, and rounded corners.
- Building custom interface components.
- Separating a screen into reusable sections.
- Managing spacing and visual organization with Auto Layout.
3.3 Creating a UIView Programmatically
import UIKit
let containerView = UIView()
containerView.backgroundColor = .systemBlue
containerView.layer.cornerRadius = 12
containerView.translatesAutoresizingMaskIntoConstraints = false
This example creates a view, gives it a system blue background, rounds its corners, and prepares it for Auto Layout constraints.
3.4 Adding a UIView to a Parent View
let containerView = UIView()
containerView.backgroundColor = .secondarySystemBackground
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
NSLayoutConstraint.activate([
containerView.leadingAnchor.constraint(
equalTo: view.leadingAnchor,
constant: 20
),
containerView.trailingAnchor.constraint(
equalTo: view.trailingAnchor,
constant: -20
),
containerView.topAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 20
),
containerView.heightAnchor.constraint(equalToConstant: 150)
])
The addSubview(_:) method inserts the container into the view hierarchy. The constraints position it 20 points from the leading and trailing edges and 20 points below the safe area's top edge.
3.5 Important UIView Properties
| Property |
Purpose |
Example |
| backgroundColor |
Sets the background color |
view.backgroundColor = .white |
| alpha |
Controls overall transparency |
view.alpha = 0.8 |
| isHidden |
Hides or shows the view |
view.isHidden = true |
| layer.cornerRadius |
Rounds the view's corners |
view.layer.cornerRadius = 10 |
| clipsToBounds |
Clips subview content to the view's bounds |
view.clipsToBounds = true |
| isUserInteractionEnabled |
Enables or disables user interaction |
view.isUserInteractionEnabled = true |
| translatesAutoresizingMaskIntoConstraints |
Controls conversion of autoresizing masks into constraints |
view.translatesAutoresizingMaskIntoConstraints = false |
3.6 Styling a UIView
containerView.backgroundColor = .systemGray6
containerView.layer.cornerRadius = 16
containerView.layer.borderWidth = 1
containerView.layer.borderColor = UIColor.systemGray3.cgColor
containerView.clipsToBounds = true
These properties create a rounded container with a subtle border. Use system colors where appropriate so the interface can adapt to appearance changes, including Light Mode and Dark Mode.
4. Understanding UILabel
4.1 What Is UILabel?
UILabel is a UIKit control used to display static or programmatically updated text. It is commonly used for headings, descriptions, field labels, status messages, prices, and confirmation messages.
A label displays information but is not intended for direct text editing by the user. When users need to enter or modify text, a text field or text view is usually more appropriate.
4.2 Creating a UILabel
import UIKit
let titleLabel = UILabel()
titleLabel.text = "Welcome to iOS Development"
titleLabel.font = .boldSystemFont(ofSize: 24)
titleLabel.textColor = .label
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
The code creates a label with bold text, centered alignment, and support for multiple lines. The system label color adapts to the current appearance.
4.3 Important UILabel Properties
| Property |
Description |
Example |
| text |
Sets the displayed string |
label.text = "Hello" |
| font |
Controls text font and size |
label.font = .systemFont(ofSize: 18) |
| textColor |
Sets the text color |
label.textColor = .label |
| textAlignment |
Aligns text horizontally |
label.textAlignment = .center |
| numberOfLines |
Controls the maximum number of lines; zero allows unlimited lines |
label.numberOfLines = 0 |
| lineBreakMode |
Controls how overflowing text is handled |
label.lineBreakMode = .byWordWrapping |
| adjustsFontSizeToFitWidth |
Allows the font to shrink to fit a single line when appropriate |
label.adjustsFontSizeToFitWidth = true |
| isHidden |
Controls visibility |
label.isHidden = false |
4.4 Updating Label Text
let statusLabel = UILabel()
statusLabel.text = "Ready"
func showSuccessMessage() {
statusLabel.text = "Form submitted successfully"
statusLabel.textColor = .systemGreen
}
A label can be updated whenever the application state changes. For example, a validation message can appear after a user submits a form.
4.5 Displaying Multiple Lines
let descriptionLabel = UILabel()
descriptionLabel.text = "Learn Swift and UIKit.\nBuild native iOS applications."
descriptionLabel.numberOfLines = 0
descriptionLabel.textAlignment = .natural
Setting numberOfLines to zero allows unlimited lines, subject to the space available in the layout. Auto Layout constraints must still provide enough room for the text to appear correctly.
4.6 Accessibility and Dynamic Type
For interfaces that support accessibility settings, prefer text styles and scalable fonts where possible.
let headingLabel = UILabel()
headingLabel.font = .preferredFont(forTextStyle: .title1)
headingLabel.adjustsFontForContentSizeCategory = true
This lets the label respond to the user's preferred text size. Ensure that the surrounding layout can expand when the font becomes larger.
5. Understanding UIButton
5.1 What Is UIButton?
UIButton is a control that responds to user interaction. Buttons are commonly used for submitting forms, navigating between screens, saving information, deleting records, opening menus, and performing actions.
Unlike a label, a button is designed for interaction. Its appearance can change according to its state, such as normal, highlighted, disabled, or selected.
5.2 Creating a UIButton
import UIKit
let submitButton = UIButton(type: .system)
submitButton.setTitle("Submit", for: .normal)
submitButton.setTitleColor(.white, for: .normal)
submitButton.backgroundColor = .systemBlue
submitButton.layer.cornerRadius = 10
submitButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
This creates a system button and configures its title and appearance. In a complete interface, add the button to a parent view and define its layout constraints.
5.3 Handling Button Taps with addTarget
import UIKit
class HomeViewController: UIViewController {
private let actionButton = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
actionButton.setTitle("Tap Me", for: .normal)
actionButton.addTarget(
self,
action: #selector(buttonTapped),
for: .touchUpInside
)
}
@objc private func buttonTapped() {
print("Button tapped")
}
}
The addTarget(_:action:for:) method connects a control event to a method. The .touchUpInside event is commonly used for a normal button tap.
5.4 Common UIButton Properties and Methods
| Property or Method |
Purpose |
| setTitle(_:for:) |
Sets the button title for a particular state |
| setTitleColor(_:for:) |
Sets the title color for a particular state |
| isEnabled |
Determines whether the button can be interacted with |
| isSelected |
Represents a selected state when the interface uses it |
| configuration |
Provides modern options for button appearance and content |
| addTarget(_:action:for:) |
Connects a control event to an action method |
| setImage(_:for:) |
Sets an image for a button state |
| tintColor |
Controls tint used by applicable button content and styling |
5.5 Disabling a Button
submitButton.isEnabled = false
submitButton.alpha = 0.5
Setting isEnabled to false prevents normal interaction. The alpha adjustment is optional because button appearance may already communicate its disabled state through the selected button style.
5.6 Modern UIButton Configuration
For newer UIKit interfaces, UIButton.Configuration provides a convenient way to define button styles and content.
let saveButton = UIButton(type: .system)
var configuration = UIButton.Configuration.filled()
configuration.title = "Save Changes"
configuration.image = UIImage(systemName: "checkmark")
configuration.imagePadding = 8
configuration.cornerStyle = .medium
saveButton.configuration = configuration
This approach is useful for creating consistent button styles. The available configuration options depend on the iOS version targeted by the application.
6. Understanding UITextField
6.1 What Is UITextField?
UITextField is a UIKit control that allows users to enter and edit a single line of text. It is commonly used for names, email addresses, passwords, search queries, phone numbers, and short form values.
For longer, multiline content, such as a message or description, UITextView is generally a better choice.
6.2 Creating a UITextField
import UIKit
let nameTextField = UITextField()
nameTextField.placeholder = "Enter your name"
nameTextField.borderStyle = .roundedRect
nameTextField.autocorrectionType = .no
nameTextField.clearButtonMode = .whileEditing
nameTextField.returnKeyType = .done
The placeholder provides a hint before the user enters text. The rounded border makes the field visually distinct, while the clear button lets users remove the current text during editing.
6.3 Important UITextField Properties
| Property |
Purpose |
Example |
| text |
Gets or sets the entered text |
textField.text = "Aarav" |
| placeholder |
Shows a hint when the field is empty |
textField.placeholder = "Email" |
| borderStyle |
Controls the field's border style |
textField.borderStyle = .roundedRect |
| keyboardType |
Chooses an appropriate keyboard layout |
textField.keyboardType = .emailAddress |
| isSecureTextEntry |
Obscures entered text for password-style fields |
textField.isSecureTextEntry = true |
| autocapitalizationType |
Controls automatic capitalization |
textField.autocapitalizationType = .none |
| autocorrectionType |
Controls text correction behavior |
textField.autocorrectionType = .no |
| returnKeyType |
Configures the keyboard's Return key label |
textField.returnKeyType = .done |
| clearButtonMode |
Controls when the clear button appears |
textField.clearButtonMode = .whileEditing |
| delegate |
Assigns an object to handle text-field events |
textField.delegate = self |
6.4 Reading User Input
let enteredName = nameTextField.text ?? ""
if enteredName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
print("Please enter your name")
} else {
print("Entered name: \(enteredName)")
}
The text property is optional, so the nil-coalescing operator provides a safe fallback. Trimming whitespace helps prevent a field containing only spaces from being accepted as valid input.
6.5 Configuring an Email Text Field
let emailTextField = UITextField()
emailTextField.placeholder = "Enter your email"
emailTextField.keyboardType = .emailAddress
emailTextField.autocapitalizationType = .none
emailTextField.autocorrectionType = .no
emailTextField.textContentType = .emailAddress
emailTextField.borderStyle = .roundedRect
These settings improve the input experience by offering a suitable keyboard and reducing unwanted automatic text changes. They do not replace email validation.
6.6 Configuring a Password Text Field
let passwordTextField = UITextField()
passwordTextField.placeholder = "Enter your password"
passwordTextField.isSecureTextEntry = true
passwordTextField.textContentType = .password
passwordTextField.autocapitalizationType = .none
passwordTextField.autocorrectionType = .no
Secure text entry obscures the visible characters in the field. It does not, by itself, securely store or transmit a password. Authentication and credential handling must be implemented using appropriate security practices.
7. Connecting Components with Interface Builder
Xcode's Interface Builder allows developers to drag UIKit components onto a storyboard or XIB and connect them to Swift code.
7.1 IBOutlet
An IBOutlet creates a connection between a visual component and a property in a view controller. It allows the code to update or inspect that component.
import UIKit
class RegistrationViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var submitButton: UIButton!
}
After adding the properties, connect each outlet to the corresponding component in Interface Builder. An implicitly unwrapped optional outlet should not be accessed before its view has loaded and the connection has been established.
7.2 IBAction
An IBAction connects a user interface event, such as a button tap, to a method in the view controller.
@IBAction func submitButtonTapped(_ sender: UIButton) {
statusLabel.text = "Button tapped"
}
Connect the button's Touch Up Inside event to this action in Interface Builder. Avoid connecting the same action twice, which could cause it to run more than once per tap.
8. Building an Interface Programmatically
UIKit components can also be created entirely in Swift. This approach is useful when an interface needs to be generated dynamically or when a project does not use storyboards.
8.1 Adding Components and Auto Layout Constraints
import UIKit
class ContactViewController: UIViewController {
private let titleLabel = UILabel()
private let nameTextField = UITextField()
private let submitButton = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
titleLabel.text = "Contact Form"
titleLabel.font = .boldSystemFont(ofSize: 24)
titleLabel.textAlignment = .center
nameTextField.placeholder = "Enter your name"
nameTextField.borderStyle = .roundedRect
nameTextField.accessibilityLabel = "Name"
submitButton.setTitle("Submit", for: .normal)
submitButton.addTarget(
self,
action: #selector(submitTapped),
for: .touchUpInside
)
let components: [UIView] = [
titleLabel,
nameTextField,
submitButton
]
components.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 40
),
titleLabel.leadingAnchor.constraint(
equalTo: view.leadingAnchor,
constant: 20
),
titleLabel.trailingAnchor.constraint(
equalTo: view.trailingAnchor,
constant: -20
),
nameTextField.topAnchor.constraint(
equalTo: titleLabel.bottomAnchor,
constant: 24
),
nameTextField.leadingAnchor.constraint(
equalTo: view.leadingAnchor,
constant: 20
),
nameTextField.trailingAnchor.constraint(
equalTo: view.trailingAnchor,
constant: -20
),
nameTextField.heightAnchor.constraint(equalToConstant: 48),
submitButton.topAnchor.constraint(
equalTo: nameTextField.bottomAnchor,
constant: 20
),
submitButton.centerXAnchor.constraint(
equalTo: view.centerXAnchor
)
])
}
@objc private func submitTapped() {
let name = nameTextField.text?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !name.isEmpty else {
titleLabel.text = "Please enter your name"
return
}
titleLabel.text = "Hello, \(name)!"
view.endEditing(true)
}
}
This example creates a heading label, a text field, and a button. Auto Layout constraints define their positions and sizes relative to the screen and one another. The button validates the input and updates the label with a greeting.
8.2 Understanding Auto Layout
Auto Layout positions and sizes views through constraints. Instead of relying only on fixed screen coordinates, constraints describe relationships between interface elements.
- Leading and trailing: Define horizontal placement while respecting layout direction.
- Top and bottom: Define vertical relationships.
- Width and height: Define a view's dimensions.
- CenterX and centerY: Align a view around another view's center.
- Safe area: Helps keep content clear of system interface areas.
When using Auto Layout programmatically, set translatesAutoresizingMaskIntoConstraints to false for views whose positions are defined by constraints. Avoid creating conflicting constraints, because they can produce unexpected layouts or constraint warnings.
9. Handling Text Field Events with UITextFieldDelegate
The UITextFieldDelegate protocol provides methods for responding to editing events, controlling whether editing begins, deciding whether characters can be entered, and handling the Return key.
9.1 Implementing the Delegate
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate {
private let usernameField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
usernameField.delegate = self
usernameField.placeholder = "Username"
usernameField.borderStyle = .roundedRect
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
When the user presses Return, resignFirstResponder() asks the text field to stop being the active input control, usually dismissing the keyboard.
9.2 Common Delegate Methods
| Delegate Method |
Purpose |
textFieldShouldBeginEditing(_:) |
Decides whether editing may begin |
textFieldDidBeginEditing(_:) |
Responds after editing begins |
textField(_:shouldChangeCharactersIn:replacementString:) |
Allows or rejects a proposed text change |
textFieldShouldReturn(_:) |
Handles the keyboard Return key |
textFieldDidEndEditing(_:) |
Responds after editing ends |
10. Input Validation and Error Messages
Input validation helps ensure that users provide information in an acceptable format before the application processes it. Validation should be clear, helpful, and appropriate to the data being entered.
10.1 Basic Required-Field Validation
func validateName(_ name: String) -> Bool {
!name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
10.2 Displaying an Error in a UILabel
let name = nameTextField.text ?? ""
if validateName(name) {
statusLabel.text = "Name accepted"
statusLabel.textColor = .systemGreen
} else {
statusLabel.text = "Please enter your name"
statusLabel.textColor = .systemRed
}
Use a clear message to explain what needs to be corrected. For complex forms, show the error near the relevant field and make the message accessible to users who rely on assistive technologies.
10.3 Improving Validation Experience
- Validate required fields before performing the main action.
- Trim accidental whitespace when appropriate.
- Choose suitable keyboard types for different kinds of input.
- Do not rely on placeholders as the only labels for important fields.
- Keep error messages specific and easy to understand.
- Do not treat client-side validation as a replacement for server-side validation.
11. Keyboard Management
When a text field becomes the first responder, iOS displays the keyboard. Applications should provide a convenient way for users to finish entering information and dismiss the keyboard when appropriate.
11.1 Dismissing the Keyboard
nameTextField.resignFirstResponder()
This asks the text field to stop being the first responder. If the user taps outside the text field, a view controller can also end editing on its view:
view.endEditing(true)
11.2 Supporting Multiple Fields
For forms containing several text fields, consider moving focus from one field to the next when the user presses Return. The final field can dismiss the keyboard or trigger validation.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTextField {
emailTextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
This example assumes both fields are properties of the same view controller and have been initialized or connected. Configure each field's delegate so the method receives its events.
12. Styling and Interface Design Best Practices
- Use consistent spacing and alignment across related controls.
- Prefer system colors such as
.systemBackground, .label, and .secondaryLabel when they suit the design.
- Use readable font sizes and support Dynamic Type where possible.
- Give interactive controls meaningful accessibility labels when their purpose is not otherwise clear.
- Make buttons visually distinguishable from labels and decorative views.
- Use suitable keyboard types for email, number, phone, and other input fields.
- Use Auto Layout to support different screen sizes and orientations.
- Provide enough room for longer text and larger accessibility font sizes.
- Use consistent corner radii and borders instead of styling every component differently.
- Keep layout logic separate from validation and business logic as the application grows.
- Test controls with VoiceOver, larger text sizes, and both Light Mode and Dark Mode.
13. Common Problems and Troubleshooting
13.1 UILabel Text Is Not Visible
Possible causes: The text property is empty, the text color blends into the background, the label has insufficient space, or its constraints are incorrect.
Solution: Check the label's text and text color, review its constraints, and confirm that it is part of the visible view hierarchy.
13.2 UIButton Does Not Respond to Taps
Possible causes: The action is not connected, the target method is missing, the button is disabled, or another view intercepts touches.
Solution: Verify the event connection or addTarget call, check isEnabled, and inspect the view hierarchy for overlapping views.
13.3 UITextField Does Not Accept Input
Possible causes: The field is disabled, interaction is turned off, or another view covers it.
Solution: Check isEnabled, isUserInteractionEnabled, the view hierarchy, and any delegate logic that prevents editing.
13.4 Auto Layout Warnings Appear
Possible causes: Constraints conflict, required dimensions are missing, or autoresizing-mask constraints conflict with manually defined constraints.
Solution: Review the console warnings, inspect the affected views, and ensure the programmatic views use translatesAutoresizingMaskIntoConstraints = false when appropriate.
13.5 Keyboard Covers a Text Field
Possible causes: The layout does not adapt when the keyboard appears, or the content is positioned too close to the bottom of the screen.
Solution: Consider a scroll view for longer forms, keyboard-aware layout adjustments, and an appropriate content layout that lets users reach every field.
13.6 IBOutlet Is Nil
Possible causes: The storyboard connection is missing or the outlet is accessed before the view has loaded.
Solution: Reconnect the outlet in Interface Builder and access it at an appropriate point in the view controller lifecycle.
14. Practical Project: Simple Registration Form
Project Objective: Create a registration interface using UIView, UILabel, UIButton, and UITextField.
14.1 Project Requirements
- Create a UIView to group the form components.
- Add a UILabel for the form heading.
- Add text fields for the user's name and email address.
- Add a UIButton to submit the form.
- Display a success or validation message in a UILabel.
- Use Auto Layout to position components.
- Dismiss the keyboard after successful submission.
14.2 Example Implementation
import UIKit
class RegistrationViewController: UIViewController {
private let formView = UIView()
private let headingLabel = UILabel()
private let nameField = UITextField()
private let emailField = UITextField()
private let submitButton = UIButton(type: .system)
private let messageLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
formView.backgroundColor = .secondarySystemBackground
formView.layer.cornerRadius = 14
headingLabel.text = "Create Account"
headingLabel.font = .boldSystemFont(ofSize: 24)
headingLabel.textAlignment = .center
nameField.placeholder = "Full name"
nameField.borderStyle = .roundedRect
nameField.autocorrectionType = .no
emailField.placeholder = "Email address"
emailField.borderStyle = .roundedRect
emailField.keyboardType = .emailAddress
emailField.autocapitalizationType = .none
emailField.autocorrectionType = .no
submitButton.setTitle("Register", for: .normal)
submitButton.configuration = .filled()
submitButton.addTarget(
self,
action: #selector(registerUser),
for: .touchUpInside
)
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.textColor = .secondaryLabel
view.addSubview(formView)
let components: [UIView] = [
headingLabel,
nameField,
emailField,
submitButton,
messageLabel
]
components.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
formView.addSubview($0)
}
formView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
formView.leadingAnchor.constraint(
equalTo: view.leadingAnchor,
constant: 20
),
formView.trailingAnchor.constraint(
equalTo: view.trailingAnchor,
constant: -20
),
formView.centerYAnchor.constraint(
equalTo: view.centerYAnchor
),
headingLabel.topAnchor.constraint(
equalTo: formView.topAnchor,
constant: 24
),
headingLabel.leadingAnchor.constraint(
equalTo: formView.leadingAnchor,
constant: 16
),
headingLabel.trailingAnchor.constraint(
equalTo: formView.trailingAnchor,
constant: -16
),
nameField.topAnchor.constraint(
equalTo: headingLabel.bottomAnchor,
constant: 24
),
nameField.leadingAnchor.constraint(
equalTo: formView.leadingAnchor,
constant: 16
),
nameField.trailingAnchor.constraint(
equalTo: formView.trailingAnchor,
constant: -16
),
nameField.heightAnchor.constraint(equalToConstant: 48),
emailField.topAnchor.constraint(
equalTo: nameField.bottomAnchor,
constant: 12
),
emailField.leadingAnchor.constraint(
equalTo: nameField.leadingAnchor
),
emailField.trailingAnchor.constraint(
equalTo: nameField.trailingAnchor
),
emailField.heightAnchor.constraint(equalToConstant: 48),
submitButton.topAnchor.constraint(
equalTo: emailField.bottomAnchor,
constant: 20
),
submitButton.centerXAnchor.constraint(
equalTo: formView.centerXAnchor
),
messageLabel.topAnchor.constraint(
equalTo: submitButton.bottomAnchor,
constant: 16
),
messageLabel.leadingAnchor.constraint(
equalTo: formView.leadingAnchor,
constant: 16
),
messageLabel.trailingAnchor.constraint(
equalTo: formView.trailingAnchor,
constant: -16
),
messageLabel.bottomAnchor.constraint(
equalTo: formView.bottomAnchor,
constant: -24
)
])
}
@objc private func registerUser() {
let name = nameField.text?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let email = emailField.text?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !name.isEmpty else {
messageLabel.text = "Please enter your name."
messageLabel.textColor = .systemRed
return
}
guard !email.isEmpty, email.contains("@") else {
messageLabel.text = "Please enter a valid email address."
messageLabel.textColor = .systemRed
return
}
messageLabel.text = "Registration details are ready, \(name)!"
messageLabel.textColor = .systemGreen
view.endEditing(true)
}
}
Note: The email check in this demonstration is intentionally basic and is not a complete email validation strategy. A production application should validate input appropriately and perform any required server-side checks. This example prepares and validates the form locally; it does not create an account or submit data to a server.
14.3 Expected Output
- The screen displays a registration card with a heading.
- The user can enter a name and email address.
- Tapping Register with an empty name displays an error message.
- An empty email or an email without an at sign displays a validation message.
- Valid-looking values display a confirmation message.
- The keyboard is dismissed after successful local validation.
15. Interview Questions and Answers
Q1. What is UIView in UIKit?
UIView is the base class for many UIKit interface elements. It provides a rectangular area for displaying content, containing subviews, handling layout, and participating in user interaction.
Q2. What is the difference between UIView and UILabel?
UIView is a general-purpose view and container, while UILabel is a specialized view designed to display text.
Q3. What is UILabel used for?
UILabel displays text such as headings, descriptions, status messages, and field captions. Users do not directly edit its text.
Q4. How do you handle a UIButton tap?
Connect an action in Interface Builder or register a target and action using addTarget(_:action:for:).
Q5. What is UITextField used for?
UITextField allows users to enter and edit a single line of text, such as a username, email address, or password.
Q6. What is the difference between placeholder and text in UITextField?
The placeholder is a hint shown when the field has no entered text. The text property contains the actual current user input.
Q7. What is the purpose of IBOutlet?
IBOutlet connects a component created in Interface Builder to a property in Swift code, allowing the application to access that component.
Q8. What is the purpose of IBAction?
IBAction connects a user interface event to a method in the view controller, such as handling a button tap.
Q9. What is Auto Layout?
Auto Layout is a constraint-based system for positioning and sizing interface elements across different screen sizes and layout conditions.
Q10. How can the keyboard be dismissed?
Call resignFirstResponder() on the active text field or use view.endEditing(true) to ask the current view hierarchy to end editing.
Q11. Why should system colors be preferred in many interfaces?
System colors can adapt to appearance settings and help maintain appropriate contrast between interface text and backgrounds.
Q12. How do you improve a form's accessibility?
Use clear labels, support Dynamic Type, provide understandable validation messages, ensure controls have appropriate accessibility information, and test the form with VoiceOver.
16. Quick Revision Checklist
- Understand UIKit's view hierarchy and the role of UIView.
- Create and style a UIView container.
- Configure UILabel text, fonts, alignment, and multiline behavior.
- Create a UIButton and respond to its tap event.
- Configure UITextField placeholders, keyboard types, and secure entry.
- Read and validate text-field input safely.
- Connect IBOutlet and IBAction in Interface Builder.
- Use Auto Layout constraints to position components.
- Handle text-field editing events with UITextFieldDelegate.
- Manage keyboard dismissal and validation messages.
- Test layouts, accessibility, and different appearance settings.
17. Conclusion
UIView, UILabel, UIButton, and UITextField are essential building blocks for creating native iOS interfaces with UIKit. UIView provides a general container and layout foundation, UILabel displays information, UIButton lets users trigger actions, and UITextField collects user input.
By combining these components with Auto Layout, appropriate event handling, validation, and accessibility practices, developers can create responsive and maintainable forms and screens. Practice building a registration or login interface to strengthen your understanding of these components in a real iOS application.
18. Course Resources