Constraints with Code #3
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 함수를 통해 기존의 설정을 변경함으로서 문제 발생을 막는다 !
작성중...
Author And Source
이 문제에 관하여(Constraints with Code #3), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@tnddls2ek/Constraints-with-Code-3저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)