TIL

28일차 TIL

h_luz 2024. 4. 4. 21:11

 

어제 해결 못한 문제들 오늘 해결해 보자...

 

 FooterView가 살짝 떠있는 오류

override func viewDidLoad() {
        
        super.viewDidLoad()
        
        //footerView 수정
        let footerView = createFooterView()
        view.addSubview(footerView)
        footerView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            footerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            footerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            footerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            footerView.heightAnchor.constraint(equalToConstant: 150) // 필요한 높이로 설정
        ])
        updateTotalAmount() //총 금액 초기화

 

viewDidLoad()에 footerView를 추가해 줘서 그냥 맨 밑에 고정되어 있도록 구현

	//footerView
    private func createFooterView() -> UIView {
        var footerView = UIView()
        let footerHeight: CGFloat = 150
        footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: footerHeight))
        footerView.backgroundColor = .white
            
        let label = UILabel()
        let formattedAmount = formatCurrency(amount: totalAmount)
        label.text = "총 결제금액  \(formattedAmount)원"
        label.translatesAutoresizingMaskIntoConstraints = false
        footerView.addSubview(label)
        self.totalPriceLabel = label
            
        let button1 = UIButton(type: .system)
        button1.setTitle("취소하기", for: .normal)
        button1.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside)
        button1.translatesAutoresizingMaskIntoConstraints = false
        footerView.addSubview(button1)
            
        button1.setTitleColor(.systemPink, for: .normal)
        button1.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button1.backgroundColor = .white
        button1.layer.cornerRadius = 10
        button1.layer.borderWidth = 0.5
        button1.layer.borderColor = UIColor.gray.cgColor
        
        let button2 = UIButton(type: .system)
        button2.setTitle("주문하기", for: .normal)
        button2.addTarget(self, action: #selector(button2Tapped), for: .touchUpInside)
        button2.translatesAutoresizingMaskIntoConstraints = false
        footerView.addSubview(button2)
        
        button2.setTitleColor(.white, for: .normal)
        button2.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button2.backgroundColor = .systemPink
        button2.layer.cornerRadius = 10
        
        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: footerView.topAnchor, constant: 30),
            label.trailingAnchor.constraint(equalTo: footerView.trailingAnchor, constant: -30), // 오른쪽으로 정렬
            
            button1.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 20),
            button1.leadingAnchor.constraint(equalTo: footerView.leadingAnchor, constant: 20),
            button1.widthAnchor.constraint(equalToConstant: 160),
            
            button2.leadingAnchor.constraint(equalTo: button1.trailingAnchor, constant: 20),
            button2.topAnchor.constraint(equalTo: button1.topAnchor),
            button2.trailingAnchor.constraint(lessThanOrEqualTo: footerView.trailingAnchor, constant: -20),
            button2.bottomAnchor.constraint(lessThanOrEqualTo: footerView.bottomAnchor, constant: -20),
            button2.widthAnchor.constraint(equalToConstant: 160),
        ])
        
        return footerView
    }

 

2 장바구니가 비어있습니다. 만들어야 함

       

       셀을 전부 삭제했을 경우

       취소하기 버튼을 눌렀을 경우

       결제 alert 창에서 예를 선택했을 경우

 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "paymentCell", for: indexPath) as! PaymentTableViewCell
	//장바구니가 비어있음
    private func updateFooterView(for isEmpty: Bool) {
        if isEmpty {
            // 장바구니가 비어있을 때의 footerView
            let emptyCartView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 50))
            let messageLabel = UILabel(frame: emptyCartView.bounds)
            messageLabel.textAlignment = .center
            messageLabel.text = "장바구니가 비었습니다."
            emptyCartView.addSubview(messageLabel)
            tableView.tableFooterView = emptyCartView
        } else {
            // 장바구니에 물건이 있을 때의 footerView
            let footerHeight: CGFloat = 150
            let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: footerHeight))
            // 이하 footerView의 내용 설정 로직 추가
            // ...
            tableView.tableFooterView = footerView
        }
    }
}

 

private func updateFooterView() {
        let isEmpty = things.isEmpty
        updateFooterView(for: isEmpty)
    }

 

셀을 전부 삭제 했을 경우

//셀 삭제 메서드
    private func deleteThing(at indexPath: IndexPath) {
        guard !things.isEmpty else {
            // 장바구니가 비었을 때
            updateFooterView(for: true)
            return
        }
            
        guard indexPath.row < things.count else {
            return // 배열의 유효하지 않은 인덱스에 대한 처리
        }
            
        things.remove(at: indexPath.row) // 데이터 배열에서 해당 항목 삭제
        tableView.deleteRows(at: [indexPath], with: .left) // 테이블 뷰에서 해당 셀 삭제
        updateTotalAmount() // 총 금액 갱신
        
        // 모든 셀을 삭제한 후 장바구니가 비었습니다 메시지를 표시할 수도 있습니다.
        if things.isEmpty {
            updateFooterView(for: true)
        }
    }

 

취소하기 버튼을 눌렀을 경우

@objc func button1Tapped() {
        let alertController = UIAlertController(title: "", message: "주문을 취소하시겠습니까?", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "확인", style: .destructive) { _ in
            // 확인 버튼을 눌렀을 때 장바구니를 비움
            self.things.removeAll()
            self.tableView.reloadData()
            self.updateTotalAmount()
            self.updateFooterView()
        }
        let cancelAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)

        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)
            
        present(alertController, animated: true, completion: nil)
    }

 

결제 alert 창에서 예를 선택했을 경우

@objc func button2Tapped() {
        let alertController = UIAlertController(title: "", message: "결제 하시겠습니까?", preferredStyle: .alert)
            
        let confirmAction = UIAlertAction(title: "예", style: .default) { _ in
            // 예 선택 시
            self.confirmOrder()
        }
        let cancelAction = UIAlertAction(title: "아니오", style: .cancel, handler: nil)
            
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)
            
        present(alertController, animated: true, completion: nil)
    }
    private func confirmOrder() {
        let alertController = UIAlertController(title: "", message: "결제가 완료되었습니다.", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "확인", style: .default) { _ in
            // 결제가 완료되었으므로 장바구니를 비우고 화면을 업데이트합니다.
            self.things.removeAll()
            self.tableView.reloadData()
            self.updateTotalAmount()
            self.updateFooterView()
        }
        alertController.addAction(confirmAction)
        present(alertController, animated: true, completion: nil)
    }

 

이 코드들 안에 updateFooterView() 함수를 사용한 것을 보면 된다!

updateFooterView()를 사용해 주면 장바구니가 비었습니다. 메시지를 볼 수 있음!

 

3 셀 삭제 시 총금액 줄어드는 거, 에러 있는 것 같음

   ㄴ 아닌가..

맞았음..

아직도 에러가 있음 ㅋㅋ

 

4 셀에 cntLabel 증가 감소해도 총금액이 안 변함

@IBAction func plusTapped(_ sender: Any) {
    plusButtonAction?()
    updatePriceLabel() // payPriceLabel 값 업데이트
    updateTotalAmount?()
}
    
@IBAction func minusTapped(_ sender: Any) {
    minusButtonAction?()
    updatePriceLabel()
    updateTotalAmount?()
}

plus, minus 버튼 탭해서 변경될 때마다 priceLabel과 updateTotalAmount를 해주면 정상적으로 작동!

 

5. 맛 세부 정보 표시하는 거 길면... 이 뜬다..

 

6. 아 그리고 Cake, Coffee, Beverage 사진 받아서 cell 이미지 설정 해야 함!

 

* 회의하면서 발견한 문제점들 해결하ㅏ기

 


 

Pull Request 공부

 

* 같은 메뉴를 골랐을 때

 

* 총 주문 메뉴 개수를 표시

 

* 밑에부터 삭제하면 괜찮은데

중간에를 막 삭제하면 마지막 셀을 삭제가 안되고 이상하게 삭제됨