Auto Layout 을 통해 상호 작용할 수 있는 직사각형꼴의 영역

언제 쓸 수 있는가?

가까이서도 레이아웃 가이드를 발견할 수 있다 👀

Untitled

간단한 레이아웃 가이드를 구현해보자 🧪

구현 내용

결과물

결과물

class ViewController: UIViewController {
    
    var layoutGuide: UILayoutGuide!
    
    var redView: UIView = {
        $0.backgroundColor = .red
        return $0
    }(UIView())
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
				/// 🔥 기본적으로 전달인자 없는 생성자를 사용하며 인스턴스를 생성한다.
        self.layoutGuide = UILayoutGuide()

				/// 🔥 LaytoutGuide 를 view 에 등록해준다.
        view.addLayoutGuide(layoutGuide)
        
        view.addSubview(redView)
        
        redView.translatesAutoresizingMaskIntoConstraints = false
        
        /// 🔥 LayoutGuide 내부 제약 잡기
				/// - 레이아웃 가이드를 이용해 내부 뷰의 레아이웃을 잡는다.
        let redLeaingConstraint = redView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor)
        
        let redTrailingConstraint = redView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor)
        
        let redTopConstraint = redView.topAnchor.constraint(equalTo: layoutGuide.topAnchor)
        
        let redBottomConstraint = redView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor)
        
        NSLayoutConstraint.activate([redLeaingConstraint, redTopConstraint, redBottomConstraint, redTrailingConstraint])
        
        /// 🔥 LayoutGuide 외부 제약 잡기
        /// - 레이아웃가이드 자체의 레이아웃을 잡아준다.
        let leadingConstraint = layoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10)
        
        let topConstraint =
            layoutGuide.topAnchor.constraint(equalTo: view.topAnchor, constant: 10)
        
        let trailingConstraint =
            layoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10)
        let bottomConstraint =
            layoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10)
        
        NSLayoutConstraint.activate([leadingConstraint, topConstraint, trailingConstraint, bottomConstraint])
    }
}

Interface Builder Library 에서는 발견할 수 없었습니다