avatar view in swift

In order to create an avatar view in Swift, you can create a custom UIView subclass that has an image view for displaying the avatar image. Here's an example implementation:

main.swift
import UIKit

class AvatarView: UIView {

    private let imageView = UIImageView()
    
    var image: UIImage? {
        get { return imageView.image }
        set { imageView.image = newValue }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupImageView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupImageView()
    }
    
    private func setupImageView() {
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: topAnchor),
            imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
            imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
            imageView.trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
    }
}
984 chars
35 lines

This implementation creates an AvatarView class that has an image property for setting the avatar image. The implementation uses an instance of UIImageView to display the image.

You can now use this AvatarView class in your view controller code as follows:

main.swift
let avatarView = AvatarView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
avatarView.image = UIImage(named: "avatar.png")
// Add the avatar view to your view hierarchy
174 chars
4 lines

In this example, the AvatarView is created with a frame, and the image property is set to a UIImage instance.

related categories

gistlibby LogSnag