Dev/SWIFT
[Swift] 커스텀 칩뷰 만들기
Laena
2024. 3. 15. 22:29
프로젝트를 진행하다가 여러가지 데이터를 삭제 추가하는 과정이 많아서
정보를 칩모양으로 담아서 x표시를 넣으면 어떨까해서
커스텀 칩뷰를 만들어봤다
참고한 레퍼런스 (네이버캘린더)
커스텀 칩뷰를 적용한 결과물
작성한 커스텀 뷰
class InfoChipView: UIView {
private let textLabel = UILabel()
private var deleteButton: UIButton?
var text: String? {
return textLabel.text
}
weak var delegate: InfoChipViewDelegate?
init(text: String, color: UIColor, showDeleteButton: Bool) {
super.init(frame: .zero)
setupTextLabel(text: text)
setupView(color: color)
if showDeleteButton {
setupDeleteButton()
} else {
textLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTextLabel(text: String) {
textLabel.text = text
textLabel.textColor = .black
addSubview(textLabel)
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
textLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
private func setupDeleteButton() {
let button = UIButton()
button.setImage(UIImage(systemName: "multiply"), for: .normal)
button.tintColor = .black
button.addTarget(self, action: #selector(deleteButtonTapped), for: .touchUpInside)
addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.leadingAnchor.constraint(equalTo: textLabel.trailingAnchor, constant: 10).isActive = true
button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
button.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
self.deleteButton = button
}
private func setupView(color: UIColor) {
backgroundColor = color
layer.cornerRadius = 3
clipsToBounds = true
}
@objc private func deleteButtonTapped() {
delegate?.didTapDeleteButton(in: self)
}
}