Constraints with Code #3

이숭인·2021년 7월 14일
0

Mastering iOS

목록 보기
7/11

Custom HeaderView

위의 두 사진처럼 switch버튼이 True or False일때, top 의 constraint를 SuperView or SafeArea 에 연결하는 방식으로 View의 위치를 조정해보자.

이것도

  • NSLayoutConstraint

  • NSLayoutAnchor

두가지 방법을 통해 구현해보자

공통

  • switch Action 설정
@IBAction func updateTopConstraint(_ sender: UISwitch) {
    if sender.isOn{
        topToSuperView?.isActive = false
        topToSafeArea?.isActive = true
    }else{
        topToSafeArea?.isActive = false
        topToSuperView?.isActive = true
    }
   }

NSLayoutConstraint

  • Constraint 설정
func layoutWithInitializer() {
     // leading, trailing, top
    blueView.translatesAutoresizingMaskIntoConstraints = false
    
    let leading = NSLayoutConstraint(item: blueView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0)
    let top = NSLayoutConstraint(item: blueView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0)
    let trailing = NSLayoutConstraint(item: blueView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0)
    let height = NSLayoutConstraint(item: blueView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100)
    
    NSLayoutConstraint.activate([leading,top, trailing, height])
    
    topToSuperView = top
    
    if #available(iOS 11.0, *) {
        topToSafeArea = NSLayoutConstraint(item: blueView, attribute: .top, relatedBy: .equal, toItem: view.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0)
    } else {
        topToSafeArea = NSLayoutConstraint(item: blueView, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
    }
   }

!!

  • iOS 11버전 이상은 view의 safeAreaLayoutGuide 가 존재하지만, 그 이전버전에서는 존재하지 않는다.
  • 따라서 기기의 iOS 버전이 11 이하인 경우, topLayoutGuide에 Constraint설정을 해야한다.

이미 지정해놓은 Constraint를 변경할 경우, 기존의 Constraint의 Active설정을 true -> false로 지정해야한다.

사용하지 않는 Constraint의 Active설정을 변경하지 않는다면, 두개의 제약이 true로 설정되어 있어서 제약끼리의 충돌이 일어나게 된다.

제약의 충돌을 막기 위해 updateTopConstraint Action 함수를 통해 기존의 설정을 변경함으로서 문제 발생을 막는다 !

작성중...

profile
iOS Developer

0개의 댓글