🍶터치더주 이어서 개발 했다.예상 화면

StackView에 "총 금액" Label과 가격을 표시하는 Label 을 만들어 구현했다.
// 왼쪽 총금액 표시 라벨
let totalAmountTitleLabel: UILabel = {
let label = UILabel()
label.text = "총 금액"
label.textColor = .font
label.textAlignment = .left
label.font = .boldSystemFont(ofSize: 20)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
// 오른쪽 금액 라벨
let totalAmountLabel: UILabel = {
let label = UILabel()
label.text = "0 원"
label.textColor = .black
label.font = .boldSystemFont(ofSize: 20)
label.textAlignment = .right
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
// 총금액 스택뷰
lazy var totalAmountStackView: UIStackView = {
// StackView 구성
// 클로저로 생성한 객체는 미리 메모리에 올라가서 self를 못 건드림.
// 따라서 lazy var 로 선언해줘야됨
let stackView = UIStackView(arrangedSubviews: [totalAmountTitleLabel, totalAmountLabel])
stackView.axis = .horizontal
stackView.spacing = 8
stackView.distribution = .equalSpacing
stackView.alignment = .center
stackView.translatesAutoresizingMaskIntoConstraints = false
// 배경 뷰처럼 스타일 주기 위해 layer 직접 적용
stackView.backgroundColor = .sub3
stackView.layer.cornerRadius = 20
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 12, left: 16, bottom: 12, right: 16)
return stackView
}()
총 금액이 장바구니의 상품에 따라 변하는 기능 구현!
// 총 금액 업데이트 메소드
func updateTotalPrice(to newPrice: Int) {
totalAmountLabel.text = "\(convertToCurrencyFormat(price: newPrice))"
}
// 총 수량 업데이트 메소드
func updateTotalQuantity(to newQuantity: Int) {
totalItemLabel.text = "총 \(newQuantity)개"
}
// 총 금액 및 총 수량 업데이트 함수
func calculateCartSummary() {
let total = cartItems.reduce(0) { $0 + ($1.item.price * $1.quantity) }
let quantity = cartItems.reduce(0) { $0 + $1.quantity }
updateTotalPrice(to: total)
updateTotalQuantity(to: quantity)
}
// 가격에 콤마 넣기
func convertToCurrencyFormat(price: Int) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 0
let result = numberFormatter.string(from: NSNumber(value: price)) ?? ""
return result
}



// 변경 전
func updateTotalPrice(to newPrice: Int) {
totalAmountLabel.text = "\(convertToCurrencyFormat(price: newPrice))"
}
// 변경 후
func updateTotalPrice(to newPrice: Int) {
totalAmountLabel.text = "\(convertToCurrencyFormat(price: newPrice)) 원"
}

많은 시행착오 끝에..

항상 저에게 도움의 손길을 주는 1정진 여러분 사랑합니다 🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶🫶