Working with Text, Buttons, Images, and Input Fields in iOS App Development
Course: iOS App Development
Topic: Working with Text, Buttons, Images, and Input Fields
Course Link: iOS App Development Training at JustAcademy
Demo Link: Register for a Free Course Demo
Official Website: JustAcademy
1. Introduction to iOS User Interface Components
User interface components are the visual elements that allow users to interact with an iOS application. They help users read information, enter data, perform actions, and view images. In native iOS development, Swift and UIKit provide several reusable components for building interactive application screens.
The four essential interface elements covered in this topic are text, buttons, images, and input fields. Understanding these components helps developers create interfaces for login screens, registration forms, profile pages, shopping applications, and other mobile applications.
Learning Objectives
- Understand the purpose of common UIKit interface components.
- Display and format text using UILabel.
- Create interactive buttons using UIButton.
- Display images using UIImageView.
- Accept user input through UITextField and UITextView.
- Connect interface components to Swift code using outlets and actions.
- Apply Auto Layout constraints to build responsive interfaces.
- Validate user input and improve accessibility.
2. Understanding UILabel for Displaying Text
UILabel is a UIKit component used to display text that users can read. It is commonly used for headings, descriptions, instructions, status messages, prices, and form labels.
A label usually displays information rather than accepting direct text editing from the user.
Common Properties of UILabel
| Property |
Purpose |
Example |
| text |
Sets the displayed text. |
label.text = "Welcome" |
| font |
Controls font family, size, and weight. |
label.font = .systemFont(ofSize: 20) |
| textColor |
Sets the text color. |
label.textColor = .label |
| textAlignment |
Controls horizontal text alignment. |
label.textAlignment = .center |
| numberOfLines |
Controls the maximum number of lines; zero allows unlimited lines. |
label.numberOfLines = 0 |
| isHidden |
Shows or hides the label. |
label.isHidden = false |
| adjustsFontSizeToFitWidth |
Allows text to shrink to fit a single line when appropriate. |
label.adjustsFontSizeToFitWidth = true |
Example: Creating and Configuring a Label
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = "Learn iOS Development"
titleLabel.font = .boldSystemFont(ofSize: 24)
titleLabel.textColor = .label
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
}
}
Explanation
titleLabel references a label connected through Interface Builder.
text specifies the content shown to the user.
.boldSystemFont(ofSize: 24) sets a bold system font with a size of 24 points.
.label uses a system color that adapts to the current interface appearance.
.center aligns the text horizontally in the label.
numberOfLines = 0 allows the label to display multiple lines when its layout permits.
3. Formatting Text and Displaying Messages
Text formatting improves readability and helps users understand the importance of information. Developers can change font sizes, weights, colors, alignment, and line spacing where appropriate.
Example: Multiple Text Styles
let heading = UILabel()
heading.text = "User Profile"
heading.font = .boldSystemFont(ofSize: 26)
heading.textColor = .label
let description = UILabel()
description.text = "Manage your personal information."
description.font = .systemFont(ofSize: 16)
description.textColor = .secondaryLabel
description.numberOfLines = 0
The system colors .label and .secondaryLabel adapt to light and dark appearances, making them useful for interfaces that support different themes.
Best Practices for Text
- Use clear and concise text.
- Maintain a logical hierarchy between headings and descriptions.
- Use readable font sizes and sufficient contrast.
- Support Dynamic Type when appropriate.
- Avoid placing long paragraphs inside small fixed-height labels.
- Use multiline labels for longer descriptions.
- Test text wrapping on different screen sizes and accessibility settings.
4. Working with UIButton
UIButton is an interactive UIKit control that allows users to perform actions by tapping or activating it. Buttons are widely used for submitting forms, navigating between screens, saving information, selecting options, and triggering calculations.
Common UIButton Properties and Methods
| Property or Method |
Purpose |
Example |
| setTitle(_:for:) |
Sets the button title for a control state. |
button.setTitle("Submit", for: .normal) |
| setTitleColor(_:for:) |
Sets the title color. |
button.setTitleColor(.white, for: .normal) |
| isEnabled |
Enables or disables interaction. |
button.isEnabled = true |
| isHidden |
Shows or hides the button. |
button.isHidden = false |
| addTarget(_:action:for:) |
Registers an event handler programmatically. |
button.addTarget(...) |
| configuration |
Configures appearance and content on supported iOS versions. |
button.configuration = .filled() |
Example: Creating a Button in Swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var submitButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
submitButton.setTitle("Submit", for: .normal)
submitButton.isEnabled = true
}
@IBAction func submitButtonTapped(_ sender: UIButton) {
messageLabel.text = "Your form has been submitted."
}
}
When the user taps the connected button, the action method executes and updates the label. The button must be connected to the IBAction in the storyboard for this example to work.
Handling Different Button States
A button can display different appearances depending on its state, such as normal, highlighted, selected, or disabled.
submitButton.setTitle("Submit", for: .normal)
submitButton.setTitle("Submitting...", for: .disabled)
submitButton.setTitleColor(.white, for: .normal)
submitButton.isEnabled = false
This example configures the normal and disabled titles and disables the button. In a real application, re-enable the button when the operation finishes or fails.
Button Design Best Practices
- Use action-oriented titles such as Save, Continue, or Submit.
- Make the button easy to identify and tap.
- Provide a visible disabled state when the action is unavailable.
- Avoid triggering the same operation multiple times accidentally.
- Use accessible labels when the visible title does not explain the purpose.
- Ensure text and button backgrounds have sufficient contrast.
5. Displaying Images with UIImageView
UIImageView displays images in a UIKit interface. It can be used for profile pictures, logos, product photos, illustrations, icons, and other visual content.
An image can come from an asset catalog, a bundled resource, or an image supplied by an application service. Remote images should be loaded using suitable asynchronous networking and caching techniques rather than blocking the main thread.
Common UIImageView Properties
| Property |
Purpose |
Example |
| image |
Sets the displayed image. |
imageView.image = UIImage(named: "profile") |
| contentMode |
Controls how the image fits within the view. |
imageView.contentMode = .scaleAspectFit |
| clipsToBounds |
Clips content to the image view's bounds. |
imageView.clipsToBounds = true |
| tintColor |
Applies a tint to compatible template images. |
imageView.tintColor = .systemBlue |
| isHidden |
Shows or hides the image view. |
imageView.isHidden = false |
| accessibilityLabel |
Provides an accessible description when appropriate. |
imageView.accessibilityLabel = "Profile photo" |
Example: Displaying an Image from Assets
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
profileImageView.image = UIImage(named: "profile")
profileImageView.contentMode = .scaleAspectFit
profileImageView.clipsToBounds = true
profileImageView.accessibilityLabel = "Profile photo"
}
}
To display the image, add an image named profile to the asset catalog and connect the UIImageView outlet in Interface Builder. The name used in code must match the asset name.
Understanding Image Content Modes
| Content Mode |
Behavior |
Common Use |
| scaleAspectFit |
Fits the entire image while preserving its aspect ratio; empty space may remain. |
Logos and diagrams. |
| scaleAspectFill |
Fills the view while preserving the aspect ratio; parts may be cropped. |
Profile and product photos. |
| scaleToFill |
Stretches the image to fill the view and may distort it. |
Use only when distortion is acceptable. |
| center |
Displays the image at its natural size centered in the view. |
Images that should not be scaled. |
Creating a Rounded Profile Image
profileImageView.contentMode = .scaleAspectFill
profileImageView.clipsToBounds = true
profileImageView.layer.cornerRadius = 50
This produces a circular-looking image when the image view is 100 by 100 points. The corner radius should generally be half the view's width and height when creating a circle.
6. Working with UITextField
UITextField is a UIKit component designed for single-line text input. It is commonly used for names, email addresses, phone numbers, passwords, and search queries.
Important UITextField Properties
| Property |
Purpose |
Example |
| text |
Reads or sets the current text. |
nameTextField.text = "Alex" |
| placeholder |
Displays a hint when the field is empty. |
nameTextField.placeholder = "Enter name" |
| keyboardType |
Chooses an appropriate keyboard layout. |
emailTextField.keyboardType = .emailAddress |
| isSecureTextEntry |
Obscures entered text for password-style fields. |
passwordTextField.isSecureTextEntry = true |
| autocorrectionType |
Controls automatic text correction. |
textField.autocorrectionType = .no |
| clearButtonMode |
Controls when the clear button appears. |
textField.clearButtonMode = .whileEditing |
| returnKeyType |
Changes the keyboard's Return key label. |
textField.returnKeyType = .done |
Example: Configuring Text Fields
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
emailTextField.placeholder = "Enter your email"
emailTextField.keyboardType = .emailAddress
emailTextField.autocorrectionType = .no
emailTextField.autocapitalizationType = .none
passwordTextField.placeholder = "Enter your password"
passwordTextField.isSecureTextEntry = true
passwordTextField.autocorrectionType = .no
}
}
Reading User Input
let email = emailTextField.text ?? ""
let password = passwordTextField.text ?? ""
if email.isEmpty || password.isEmpty {
print("Please complete all required fields.")
} else {
print("Required fields have been entered.")
}
This example checks whether the fields contain text. It does not authenticate a user or establish that the supplied information is valid.
7. Working with UITextView
UITextView is used for displaying or accepting multiline text. Unlike UITextField, which is intended for single-line entry, UITextView is suitable for comments, feedback, biographies, notes, and longer descriptions.
Example: Configuring a Text View
import UIKit
class FeedbackViewController: UIViewController {
@IBOutlet weak var feedbackTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
feedbackTextView.font = .systemFont(ofSize: 16)
feedbackTextView.text = ""
feedbackTextView.layer.borderWidth = 1
feedbackTextView.layer.borderColor =
UIColor.separator.cgColor
feedbackTextView.layer.cornerRadius = 8
}
}
In this example, the text view is configured with a readable font, a subtle border, and rounded corners. If a placeholder is required, implement one using an appropriate design pattern, such as a separate label or a carefully managed text view delegate.
UITextField vs UITextView
| Feature |
UITextField |
UITextView |
| Input length |
Designed for single-line input. |
Supports multiline text. |
| Typical use |
Email, name, password. |
Feedback, comments, notes. |
| Return key handling |
Often configured to finish or advance editing. |
Usually inserts a new line unless configured otherwise. |
| Delegate protocol |
UITextFieldDelegate. |
UITextViewDelegate. |
8. Connecting Interface Elements with Outlets and Actions
Interface elements created in a storyboard must be connected to Swift code when the application needs to access them or respond to their events.
Creating an Outlet
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameTextField: UITextField!
These properties provide references to a label, an image view, and a text field. Connect each property to its corresponding interface element in Interface Builder.
Creating an Action
@IBAction func saveButtonTapped(_ sender: UIButton) {
titleLabel.text = "Information saved."
}
Connect the button's Touch Up Inside event to this action. When the user activates the button, the method updates the label.
Connection Checklist
- Confirm that the correct view controller class is assigned.
- Ensure each IBOutlet is connected to the intended element.
- Connect each IBAction to the appropriate control and event.
- Remove outdated connections after renaming or deleting properties.
- Test each interaction in the simulator.
9. Mini Project: User Profile Screen
Project Objective: Build a profile screen that displays an image, shows text, accepts a user's name, and responds to a button tap.
Interface Requirements
- A UILabel displaying the heading "User Profile".
- A UIImageView showing a profile image.
- A UITextField allowing the user to enter a name.
- A UIButton labelled "Update Profile".
- A UILabel displaying a greeting or validation message.
Swift Implementation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var headingLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var updateButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
headingLabel.text = "User Profile"
headingLabel.font = .boldSystemFont(ofSize: 24)
profileImageView.image = UIImage(named: "profile")
profileImageView.contentMode = .scaleAspectFill
profileImageView.clipsToBounds = true
nameTextField.placeholder = "Enter your name"
resultLabel.text = "Your profile message will appear here."
updateButton.setTitle("Update Profile", for: .normal)
}
@IBAction func updateProfileTapped(_ sender: UIButton) {
let name = nameTextField.text?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !name.isEmpty else {
resultLabel.text = "Please enter your name."
return
}
resultLabel.text = "Welcome, \(name)!"
view.endEditing(true)
}
}
Project Explanation
- The heading label displays the profile screen title.
- The image view displays an image from the asset catalog.
- The text field accepts the user's name.
- The Update Profile button triggers the connected action.
- The action removes leading and trailing whitespace from the input.
- If the input is empty, the application displays a validation message.
- If the input is valid, the application displays a personalized greeting.
- The keyboard is dismissed after a successful update.
Note: Connect every outlet and the button action in Interface Builder. Add the image asset named profile to the project. The example updates the interface only; it does not save profile information to permanent storage or a server.
10. Applying Auto Layout to Interface Components
Auto Layout allows interface elements to adapt to different screen sizes, device orientations, and content lengths. Rather than relying entirely on fixed coordinates, developers define relationships between views using constraints.
Common Layout Constraints
| Constraint |
Purpose |
Example |
| Center X |
Horizontally centers a view. |
Center a logo on the screen. |
| Center Y |
Vertically centers a view. |
Center a loading indicator. |
| Leading and Trailing |
Define horizontal spacing. |
Align a text field within screen margins. |
| Top and Bottom |
Define vertical positioning. |
Place a heading above an input field. |
| Width and Height |
Control dimensions. |
Set a consistent button height. |
| Aspect Ratio |
Maintains a proportional relationship. |
Preserve an image's shape. |
Example: Programmatic Constraints
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 24
),
titleLabel.leadingAnchor.constraint(
equalTo: view.leadingAnchor,
constant: 20
),
titleLabel.trailingAnchor.constraint(
equalTo: view.trailingAnchor,
constant: -20
)
])
This example positions the label below the safe area's top edge and provides horizontal margins. The label must already belong to the view hierarchy, and other components should receive appropriate constraints as well.
11. Input Validation and User Feedback
Input validation checks whether the information entered by a user meets the application's requirements. It helps prevent incomplete forms and improves the user experience.
Example: Validating a Required Name
func validateName(_ name: String) -> Bool {
return !name.trimmingCharacters(
in: .whitespacesAndNewlines
).isEmpty
}
This function returns true when the input contains at least one non-whitespace character.
Validation Best Practices
- Validate required fields before processing form submissions.
- Provide clear messages explaining how to correct an error.
- Use appropriate keyboard types for each field.
- Avoid clearing all fields when one validation error occurs.
- Perform authoritative validation on the server when data is submitted to a backend.
- Do not rely on client-side validation as a security mechanism.
- Never display or log sensitive information unnecessarily.
12. Accessibility Considerations
Accessible interfaces make applications easier to use for people with different abilities and preferences.
- Provide meaningful accessibility labels for images that convey information.
- Mark purely decorative images appropriately so assistive technologies can ignore them.
- Use descriptive button titles and accessible control traits.
- Support Dynamic Type where possible.
- Maintain sufficient contrast between text and backgrounds.
- Ensure controls have comfortable touch targets.
- Do not communicate important status information through color alone.
- Test the application with VoiceOver and accessibility settings.
13. Common Errors and Troubleshooting
| Issue |
Cause |
Solution |
| Label does not display text |
Text is not assigned or the wrong label is connected. |
Check the IBOutlet and assigned text. |
| Button tap has no effect |
The action is not connected to the correct event. |
Inspect the Connections Inspector. |
| Image does not appear |
The asset name is incorrect or the image is missing. |
Verify the asset catalog entry and image name. |
| Image looks stretched |
The selected content mode distorts the image. |
Use scaleAspectFit or scaleAspectFill as appropriate. |
| Text field returns an empty value |
No text was entered or the wrong field is referenced. |
Verify the outlet and validate the input. |
| Keyboard covers the form |
The interface does not accommodate keyboard presentation. |
Use suitable scrolling, keyboard handling, or layout adjustments. |
| Interface looks incorrect on another device |
Constraints are missing or inflexible. |
Review Auto Layout and test different screen sizes. |
| Outlet connection causes a crash |
An outlet is nil when accessed. |
Reconnect the outlet and inspect the runtime error. |
14. Practical Exercises
Exercise 1: Welcome Screen
- Create a heading label and a description label.
- Apply different font sizes and weights.
- Align the labels using Auto Layout.
- Test the screen in light and dark appearance modes.
Exercise 2: Interactive Button
- Create a button and a status label.
- Connect the button to an IBAction.
- Update the label when the button is tapped.
- Test the enabled and disabled button states.
Exercise 3: Image Gallery
- Add three images to the asset catalog.
- Display one image using UIImageView.
- Add Next and Previous buttons.
- Update the displayed image when either button is tapped.
- Prevent the image index from moving outside the available range.
Exercise 4: Registration Form
- Create name, email, and password fields.
- Set appropriate keyboard and secure-entry properties.
- Add a Register button and a status label.
- Validate required fields before displaying a local success message.
- Test empty input and invalid formats.
15. Interview Questions and Answers
Q1. What is UILabel?
UILabel is a UIKit component used to display text in an iOS interface.
Q2. What is UIButton?
UIButton is an interactive control that allows users to trigger actions by tapping or activating it.
Q3. What is UIImageView?
UIImageView displays images in a UIKit interface, such as logos, profile pictures, and product images.
Q4. What is UITextField?
UITextField is a control designed primarily for single-line text input.
Q5. What is the difference between UITextField and UITextView?
UITextField is designed for single-line input, while UITextView supports multiline text entry and display.
Q6. What is the purpose of the placeholder property?
The placeholder provides a hint about the expected input while a text field is empty.
Q7. What is the purpose of contentMode in UIImageView?
It determines how an image is scaled or positioned within its image view.
Q8. What is the difference between scaleAspectFit and scaleAspectFill?
ScaleAspectFit displays the complete image while preserving its proportions. ScaleAspectFill fills the view while preserving proportions, potentially cropping some of the image.
Q9. How do you handle a button tap in UIKit?
Connect an IBAction to a control event in Interface Builder or register a target-action handler programmatically.
Q10. Why is Auto Layout important?
Auto Layout defines relationships between interface elements so that layouts can adapt to different screen sizes and content.
Q11. How can you hide password text?
Set the password text field's isSecureTextEntry property to true.
Q12. Why is input validation important?
Input validation helps detect missing or incorrectly formatted information before the application processes it.
16. Quick Revision Checklist
- UILabel displays text and status messages.
- UIButton triggers user actions.
- UIImageView displays image content.
- UITextField accepts single-line text input.
- UITextView supports multiline text.
- IBOutlet connects interface components to Swift properties.
- IBAction connects interface events to Swift methods.
- Auto Layout helps interfaces adapt to different devices.
- Input validation improves reliability and usability.
- Accessibility and responsive layouts should be considered during development.
17. Conclusion
Text, buttons, images, and input fields are fundamental components of native iOS application development. UILabel presents information, UIButton allows users to perform actions, UIImageView displays visual content, and UITextField or UITextView collects user input.
By combining these components with Swift, UIKit, Interface Builder, Actions, Outlets, and Auto Layout, developers can build interactive screens for real-world applications. Regular practice with profile screens, registration forms, and image galleries helps develop the skills needed for more advanced iOS development topics.
Learn More with JustAcademy
Explore structured iOS app development training and strengthen your practical skills in Swift, UIKit, and Xcode.
Course Details: Explore the iOS App Development Training Course
Free Demo: Register for a Course Demo
Official Website: Visit JustAcademy