관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] 2. Autolayout 고급 (with SnapKit) - remakeConstraints, multipliedBy, dividedBy 본문

UI 컴포넌트 (swift)

[iOS - swift] 2. Autolayout 고급 (with SnapKit) - remakeConstraints, multipliedBy, dividedBy

jake-kim 2022. 2. 3. 02:41

1. Autolayout 고급 (with SnapKit) - Hugging, Compression, priority 개념

2. Autolayout 고급 (with SnapKit) - remakeConstraints, multipliedBy, dividedBy

3. Autolayout 고급 (with SnapKit) - Constraint 프로퍼티를 사용한 단순한 animation 구현

4. Autolayout 고급 (with SnapKit) - Stretchy 레이아웃 구현

autolayout으로 구현한 progress UI

미리 알아야하는 개념

  • 코드로 UI 구현 시, SnapKit 기본 사용 방법
  • snapKit의 remakeConstraints()
    • 기존에 입력되었던 constraints를 삭제하고 다시 constraints를 설정하는 메소드
  • multipliedBy, dividedBy
    • dividedBy
      self.view.addSubview(self.leftButton)
      self.view.addSubview(self.rightButton)
      self.leftButton.snp.makeConstraints {
        $0.left.equalToSuperview()
        $0.width.equalToSuperview().dividedBy(2) // <-
        $0.top.equalTo(self.progressContainerView.snp.bottom).offset(32)
      }
      self.rightButton.snp.makeConstraints {
        $0.right.equalToSuperview()
        $0.width.equalToSuperview().dividedBy(2) // <-
        $0.top.equalTo(self.progressContainerView.snp.bottom).offset(32)
      }​

    • 위 dividedBy부분을 multipliedBy(1.0/2.0)으로 하면 동일한 UI 완성

Progress 구현 아이디어

  • UIView 2개를 준비
    • 로딩 뷰의 회색 부분의 배경을 담당할 progressContainerView
    • 로딩 뷰의 파란색 진행 사항을 표출할 progressView (progressContainerView에 addSubview)
  • progress가 변경될 때마다 remakeConstraints를 통해 progressView의 width값을 업데이트
  • progressView의 width값을 업데이트 시키고 싶은 경우 multipliedBy를 사용하여 편리하게 구현

Progress 구현

  • UI 준비
    • progress container 뷰 (예제에서는 UIView를 따로 썼지만, self.backgroundColor를 이용하면 해당 뷰 불필요)
    • progress 뷰
      private let progressContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .gray
        return view
      }()
      private let progressView: UIView = {
        let view = UIView()
        view.backgroundColor = .systemBlue
        return view
      }()
  • addSubview
    self.view.addSubview(self.progressContainerView)
    self.progressContainerView.addSubview(self.progressView)​
  • 레이아웃 초기화
    self.progressContainerView.snp.makeConstraints {
      $0.top.equalTo(self.view.safeAreaLayoutGuide)
      $0.left.right.equalToSuperview().inset(32)
      $0.height.equalTo(20)
    }
    self.progressView.snp.makeConstraints {
      $0.left.bottom.top.equalToSuperview()
      $0.width.equalToSuperview().multipliedBy(progress / finish)
    }​
  • progress가 업데이트 될 때마다 remakeConstraints를 사용하여 layout 업데이트
    updateProgress { [weak self] in
      self?.progressView.snp.remakeConstraints {
        $0.left.bottom.top.equalToSuperview()
        $0.width.equalToSuperview().multipliedBy(progress / finish)
      }
    }​

* 최적화된 ProgressBar 구현 방법은 ProgressBar 구현 방법 포스팅 글 참고


* 전체 코드: https://github.com/JK0369/ExAutolayout/tree/Chapter2

Comments