선택적인 뷰 활성화

1 답변 글타래를 보이고 있습니다
  • 글쓴이
    • iJoom
      참가자
      • 글작성 : 8
      • 답글작성 : 1

      선택적인 뷰 활성화


      스크린샷 2020-04-18 오전 12 56 57

      • 숙박,식사,주류 및 간식 카테고리만 필요하고 나머지 카테고리는 필요없게 선택했다면?

      import UIKit class tempViewController: UIViewController {         @IBOutlet weak var hotelViewBttn: UIButton!     @IBOutlet weak var restaurantViewBttn: UIButton!     @IBOutlet weak var drinkViewBttn: UIButton!     @IBOutlet weak var transportViewBttn: UIButton!     @IBOutlet weak var shoppingViewBttn: UIButton!     @IBOutlet weak var activityViewBttn: UIButton!   //Button을 이용해 선택한 객체만 뷰를 생성 및 활성화     @IBOutlet weak var completeBttn: UIButton!          /*처음 default 선택이 6개이므로*/          var infoOfDate : [String:String] = ["city" : "null", "fromDate" : "null", "toDate" : "null"] // cityname          var numOfselected : Int = 6 //선택된 카테고리 갯수 //    shared.selectedCategory : [String : Bool] = ["hotel" : true, "restaurant" : true, "drink" : true, "transport" : true, "shopping" : true, "activity" : true] //선택된거 true로 바뀜    // selectedCategory는 뷰의 숫자구성을 하나씩 없애면서 다음 뷰로 전달     var selectedCategoryData : [Int] = [0,1,2,3,4,5] //카테고리 고른거 순서대로 뷰 띄우기 위해서     // custom view shadow 만들기     func makeShadow(outerView : UIView){         outerView.clipsToBounds = false         outerView.layer.shadowColor = UIColor.gray.cgColor         outerView.layer.shadowOpacity = 0.1         outerView.layer.shadowOffset = CGSize(width: 23, height: 10)         outerView.layer.shadowRadius = 3         outerView.layer.shadowPath = UIBezierPath(roundedRect: outerView.bounds, cornerRadius: 10).cgPath     }          override func viewWillAppear(_ animated: Bool) {          self.navigationController?.isNavigationBarHidden = false     }          override func viewDidLoad() {         super.viewDidLoad()                // 클릭시 바뀌는 이벤트일 때 처음에 else문부터 들어가서, 두번클릭해야 바뀌는거 방지       // 코드로 인한 버튼 normal로 셋팅         hotelViewBttn.setImage(UIImage(named: "btnMakeStayMinus"), for: .normal)         restaurantViewBttn.setImage(UIImage(named: "btnMakeFoodMinus"), for: .normal)         drinkViewBttn.setImage(UIImage(named: "btnMakeSnacksMinus"), for: .normal)         transportViewBttn.setImage(UIImage(named: "btnMakeTrafficMinus"), for: .normal)         shoppingViewBttn.setImage(UIImage(named: "btnMakeShoppingMinus"), for: .normal)         activityViewBttn.setImage(UIImage(named: "btnMakeActivityMinus"), for: .normal)                       }         

      enumerated() – 공식 문서 함수 설명

      Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

      Return Value

      A sequence of pairs enumerating the sequence.

      한마디로, Array의 값과 index을 한쌍으로서 찍어내게해줌


      for (n, c) in "Swift".enumerated() {     print("\(n): '\(c)'") } // Prints "0: 'S'" // Prints "1: 'w'"

       /*버튼 이미지가 -일때는 클릭시 +로, +일때는 -로/ 라벨 색 회색 변경*/     @IBAction func pressHotelViewBttn(_ sender: Any) {         if hotelViewBttn.image(for: .normal) == UIImage(named: "btnMakeStayMinus"){             hotelViewBttn.setImage(UIImage(named: "btnMakeStayPlus"), for: .normal)             numOfselected = numOfselected - 1             TotalPlanData.shared.selectedCategory["hotel"] = false             for (i, v) in selectedCategoryData.enumerated(){                 if v == 0{                     selectedCategoryData.remove(at: i)                 }             }         }         else{                         hotelViewBttn.setImage(UIImage(named: "btnMakeStayMinus"), for: .normal)             numOfselected = numOfselected + 1             TotalPlanData.shared.selectedCategory["hotel"] = true             selectedCategoryData.append(0)         }         /*전체 해제시 선택완료 버튼 비활성화*/         if numOfselected == 0{             completeBttn.isEnabled = false         }         else{             completeBttn.isEnabled = true         }         selectedCategoryData.sort()         print(selectedCategoryData)     }     @IBAction func pressRestaurantViewBttn(_ sender: Any) {         if restaurantViewBttn.image(for: .normal) == UIImage(named: "btnMakeFoodMinus"){             restaurantViewBttn.setImage(UIImage(named: "btnMakeFoodPlus"), for: .normal)             numOfselected = numOfselected - 1             TotalPlanData.shared.selectedCategory["restaurant"] = false             for (i, v) in selectedCategoryData.enumerated(){                 if v == 1{                     selectedCategoryData.remove(at: i)                 }             }         }                      else{             restaurantViewBttn.setImage(UIImage(named: "btnMakeFoodMinus"), for: .normal)             numOfselected = numOfselected + 1             TotalPlanData.shared.selectedCategory["restaurant"] = true             selectedCategoryData.append(1)         }         /*전체 해제시 선택완료 버튼 비활성화*/         if numOfselected == 0{                    completeBttn.isEnabled = false                }                else{                    completeBttn.isEnabled = true                }         selectedCategoryData.sort()         print(selectedCategoryData)     }            }
      • 위의 코드로 내가 원하는 카테고리에 맞는 CategoryData 구성
      • EX) 1,3,5 번 카테고리(뷰)만 선택


      주의) 일부러 하드코딩된 코드를 보여드립니다. (이렇게 X)

      어떻게 하면 간결하게 만들 수 있을까요? 생각해봅시다. (해결방안은 밑에)

      • if let nextCategory = selectedCategoryData.first

      • nextCategory의 값에만 맞는 뷰컨으로 push만 해주면 됨

      • But…..


      @IBAction func showNextCategory(_ sender: Any) {         let backItem = UIBarButtonItem()             backItem.title = ""             navigationItem.backBarButtonItem = backItem                  if let nextCategory = selectedCategoryData.first{                          if nextCategory == 0{                 let vc = storyboard?.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController                 var tmpSelectedCategory = selectedCategoryData                 tmpSelectedCategory.remove(at: 0)                 vc.selectedCategoryData = tmpSelectedCategory                 vc.pgValue = numOfselected                 self.navigationController?.pushViewController(vc, animated: true)             }                          if nextCategory == 1{                 let vc = storyboard?.instantiateViewController(withIdentifier: "CategoryFoodViewController") as! CategoryFoodViewController                 var tmpSelectedCategory = selectedCategoryData                 tmpSelectedCategory.remove(at: 0)                 vc.selectedCategoryData = tmpSelectedCategory                 vc.pgValue = numOfselected                 self.navigationController?.pushViewController(vc, animated: true)             }                          if nextCategory == 2{                 let vc = storyboard?.instantiateViewController(withIdentifier: "CategoryDrinkViewController") as! CategoryDrinkViewController                 var tmpSelectedCategory = selectedCategoryData                 tmpSelectedCategory.remove(at: 0)                 vc.selectedCategoryData = tmpSelectedCategory                 vc.pgValue = numOfselected                 self.navigationController?.pushViewController(vc, animated: true)                              }                          if nextCategory == 3{             let vc = storyboard?.instantiateViewController(withIdentifier: "CategoryTransportViewController") as! CategoryTransportViewController             var tmpSelectedCategory = selectedCategoryData             tmpSelectedCategory.remove(at: 0)             vc.selectedCategoryData = tmpSelectedCategory             vc.pgValue = numOfselected             self.navigationController?.pushViewController(vc, animated: true)             }                          if nextCategory == 4{                 let vc = storyboard?.instantiateViewController(withIdentifier: "CategoiryShoppingViewController") as! CategoiryShoppingViewController                 var tmpSelectedCategory = selectedCategoryData                 tmpSelectedCategory.remove(at: 0)                 vc.selectedCategoryData = tmpSelectedCategory                 vc.pgValue = numOfselected                 self.navigationController?.pushViewController(vc, animated: true)             }                          if nextCategory == 5{                 let vc = storyboard?.instantiateViewController(withIdentifier: "ActivityCellViewController") as! ActivityCellViewController                 var tmpSelectedCategory = selectedCategoryData                 tmpSelectedCategory.remove(at: 0)                 vc.selectedCategoryData = tmpSelectedCategory                 vc.pgValue = numOfselected                 self.navigationController?.pushViewController(vc, animated: true)                              }

      위의 방법 처럼 X

      for문, Sotryboard ID를 String 배열로 만들면 문제해결 가능

      • ex) [“HotelVC”,”ActivityVC”,”333VC”,”4444VC”]

      • nextCategory가 영이라면 배열의 0인덱스 값이 스토리보드 아이디가 되므로

      스크린샷 2020-04-18 오전 12 57 09

      카테고리 뷰를 벗어나서 그 다음 뷰컨에서 내가 선택한 카테고리 순서대로 이동


      selectedCategoryData : [Int] = [] 
      • 다음 뷰컨에서 카테고리에 맞는 순서를 전달 받고 해당에 맞는 숫자(뷰)를 제거 해주고

      • selectedCategoryData의 첫번째의 숫자에 맞는 카테고리로 뷰컨 이동

      • 이 과정을 반복하면, 앞에 카테고리 화면에서 활성화 된 뷰에만 맞는 뷰들로만 뷰컨이 뛰어지게 됨 


      if selectedCategoryData.count == 0{             //go to next category flow             let vc = storyboard?.instantiateViewController(withIdentifier: "totalBudgetViewController") as! totalBudgetViewController                            self.navigationController?.pushViewController(vc, animated: true)         }         if selectedCategoryData.count > 0 {           //selectedCategoryData의 첫번째 데이터의 뷰로 푸쉬           //푸쉬 하면서 해당 뷰의 숫자 제거           // ex) 1,3,4,5 -> 3,4,5 -> 4,5         }

      더 좋은 방법이 있다면 제보해주세욥

    • 야곰
      키 마스터
      • 글작성 : 37
      • 답글작성 : 580

      좋은 글이네요 🙂 enumerate 메서드를 유용하게 사용하셨네요 ㅎㅎ
      infoOfDate 딕셔너리는 사용하지 않는 것 같은데 선언이 되어있는데 이유가 있을까요?
      그리고 var infoOfDate : [String:String] = ["city" : "null", "fromDate" : "null", "toDate" : "null"] 대신에 var infoOfDate : [String:String] = ["city" : nil, "fromDate" : nil, "toDate" : nil] 이렇게 하지 않은 이유도 궁금합니다 🙂

1 답변 글타래를 보이고 있습니다
  • 답변은 로그인 후 가능합니다.

logo landscape small

사업자번호 : 743-81-02195
통신판매업 신고번호 : 제 2022-충북청주-1278 호
고객센터 : 카카오톡채널 @yagom