IOS INTERVIEW QUESTIONS DAY 34
Basic UIKit Components (UILabel, UITextField, UIButton)
1️⃣ Explain the role of UILabel in iOS applications.
UILabel
is a fundamental UI component in iOS applications, used for displaying a small to moderate amount of text that does not need user interaction. Its primary role is to present static content, such as titles, descriptions, or any text-based information to the user
Example:
In a weather application, you might use a UILabel
to display the current temperature, where the text is updated frequently based on weather data, but the user does not interact with it directly.
2️⃣ How do you create a custom UIButton with an image in Swift?
Creating a custom UIButton
with an image involves configuring the button's appearance and adding the image either as a background image or a standard image, depending on the use case.
Example:
In this example, the button displays an image alongside the text. The setImage(_:for:)
method adds the image, and the button's appearance is customized further with background color and text color.
3️⃣ What are the common use cases for UITextField?
UITextField
is used for single-line text input in iOS applications. It’s commonly employed in forms, search bars, and login screens where users need to enter text, such as names, emails, or passwords.
Example Use Cases:
- Login Screen: For entering a username and password.
- Search Bar: For entering search queries.
- Form Inputs: For entering details like name, email, and address in a form.
4️⃣ Describe the difference between addTarget and IBAction for UIButton events.
addTarget
and IBAction
are used to connect a UIButton
to a method that will be called when an event occurs, such as a button tap. The key differences are in their usage and flexibility.
Example:
addTarget:
This is a programmatic way to connect actions to a button. It’s useful when you want to add multiple targets to a button or handle events dynamically in code
Example:
IBAction:
This is more commonly used in Interface Builder (storyboards) and is tied directly to a method via a control-drag in the UI. It’s convenient for quick setup but less flexible for complex scenarios.
5️⃣ How can you dynamically change the text of a UILabel in Swift?
You can dynamically change the text of a UILabel
by directly assigning a new value to its text
property. This is useful when the label’s content needs to be updated based on user interactions or real-time data.
Example:
- Suppose you have a button that, when tapped, should change the text of a
UILabel
to "Hello, World!":
In this example, tapping the button triggers the changeLabelText
function, which updates the label's text property.