import UIKit
protocol User {
var name: String { get }
var age: Int { get }
var email: String { get }
}
struct UserModel: User {
let name: String
let age: Int
let email: String
}
protocol UserDisplayable {
func display(user: User)
}
class UserProfileViewController: UIViewController, UserDisplayable {
private let nameLabel = UILabel()
private let ageLabel = UILabel()
private let emailLabel = UILabel()
private let editButton = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupUI()
let user = UserModel(name: "John Appleseed", age: 28, email: "john@apple.com")
display(user: user)
}
func setupUI() {
nameLabel.translatesAutoresizingMaskIntoConstraints = false
ageLabel.translatesAutoresizingMaskIntoConstraints = false
emailLabel.translatesAutoresizingMaskIntoConstraints = false
editButton.translatesAutoresizingMaskIntoConstraints = false
nameLabel.font = UIFont.systemFont(ofSize: 18, weight: .bold)
ageLabel.font = UIFont.systemFont(ofSize: 16)
emailLabel.font = UIFont.systemFont(ofSize: 16)
editButton.setTitle("Edit Profile", for: .normal)
editButton.addTarget(self, action: #selector(editProfileTapped), for: .touchUpInside)
view.addSubview(nameLabel)
view.addSubview(ageLabel)
view.addSubview(emailLabel)
view.addSubview(editButton)
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
nameLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
ageLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 20),
ageLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),
emailLabel.topAnchor.constraint(equalTo: ageLabel.bottomAnchor, constant: 20),
emailLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),
editButton.topAnchor.constraint(equalTo: emailLabel.bottomAnchor, constant: 40),
editButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
func display(user: User) {
nameLabel.text = "Name: \(user.name)"
ageLabel.text = "Age: \(user.age)"
emailLabel.text = "Email: \(user.email)"
}
@objc func editProfileTapped() {
print("Edit tapped")
}
}
We defined a User protocol with the required properties. Then, UserModel struct conforms to it, holding actual user data.
The UserDisplayable protocol declares a method to display user info. The UserProfileViewController conforms to this protocol and implements the method to update UI labels.
The UI is built programmatically with labels and a button. The button triggers a method that prints a message when tapped, simulating an edit action.