[AutoLayout] make constraint programmatically

정유진·2022년 10월 7일
0

swift

목록 보기
13/24
post-thumbnail

언제 사용하면 좋을까?

  • storyboard를 사용하지 않을 때
  • snapkit을 사용하지 않을 때

1) 써도 된다면 snapkit을 쓰겠지만

override func viewDidLoad() {
	super.viewDidLoad()
    layout()
}

private func layout() {
	view.addSubview(superViewBase)
    superViewBase.snp.makeConstraints {
    	$0.deges.equalToSuperview().offset(20)
        //...
    }
}

2) 외부 라이브러리 의존없이 코드로만 constraint 만들기

  • UIView에서 .superview는 부모 뷰를 의미한다. 현재의 viewController는 keyWindow의 rootViewController라서 view.superview = nil
  • 만약 superViewBase.addSubview(subViewBase) 한다면, subViewBase.superview는 superViewBase 일 것이다. (부모 뷰니까)
  • navigation bar의 anchor를 넘어서고 싶지 않을 때 기준을 safeAreaLayourGuide 로 잡아주면 안전하다.
  • .isActive = true 해야 적용된다.
  • 우리가 storyboard에서 컴포넌트 끼리 constraint를 잡아주던 것처럼 NSLayoutConstraint 에서 item (constraint를 주고 싶은 컴포넌트), toItem (기준이 될 컴포넌트), attribute parameter를 통해 같은 효과를 낼 수 있다.
class MainViewController: UIViewController {
    
    private lazy var superViewBase: UIView = {
        var view = UIView()
        view.backgroundColor = .gray
        return view
    }()
    
    private lazy var subViewBase: UIView = {
        var view = UIView()
        view.backgroundColor = .blue
        return view
    }()
    
  override func viewDidLoad() {
      super.viewDidLoad()
      layout()
   }

  private func layout() {     
     view.addSubview(superViewBase)
     superViewBase.translatesAutoresizingMaskIntoConstraints = false 

     superViewBase.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
     superViewBase.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
     NSLayoutConstraint(item: superViewBase,
                        attribute: .top,
                        relatedBy: .equal,
                        toItem: view.safeAreaLayoutGuide,
                        attribute: .top,
                        multiplier: 1.0,
                        constant: 16).isActive = true
     /*
      subViewBase.snp.makeConstraints {
        $0.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(16)
     }
     */
                        
     superViewBase.heightAnchor.constraint(equalToConstant: 400).isActive = true
     //...
    }

출처 표기 👏

참고자료
https://developer.apple.com/documentation/uikit/nslayoutanchor/1500937-constraint

profile
느려도 한 걸음 씩 끝까지

0개의 댓글