code로 UI작성 사용법

작성일

UIView

    var greenBox: UIView = {
        let view = UIView()
        view.backgroundColor = .green
        return view
    }()

이런식으로 작성하면 된다.

imageView

    private lazy var profileImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = true
        iv.setDimensions(width: 40, height: 40)
        iv.layer.cornerRadius = 40 / 2
        iv.backgroundColor = .twitterBlue
        return iv
    }()

Label

    private let usernameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 14)
        label.text = "Username"
        return label
    }()

Button1

    private lazy var commentButton: UIButton = {
        let button = createButton(withImageName: "comment")
        button.addTarget(self, action: #selector(handleCommentTapped), for: .touchUpInside)
        return button
    }()

Button2

    lazy var myButton = { (color: UIColor) -> UIButton in
        let btn = UIButton(type: .system)
        btn.backgroundColor = color
        btn.setTitle("내 버튼", for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40)
        btn.layer.cornerRadius = 16
        btn.clipsToBounds = true
        return btn
    }

이렇게 만든후, 사용할때

let myDarkGrayBtn = myButton(.darkGray)

이런식으로 색상을 넣어서 사용할 수 도 있다. (사실 이걸 위한 글이기도 하다.)