본문 바로가기
iOS

[iOS] AutoLayout programmatical 하게 구성하기

by teamnova 2022. 1. 28.

오토레이아웃은 처음 접할 때 꽤 힘들게 느껴지기 마련입니다. 

 

포스팅 한번에 끝내기 보다는 시리즈로 하나하나 차근차근 접근하는게 좋을 것 같아 기획하게 되었는데요 그럼 먼저 

 

코드로 구현하는 방법이 세가지가 있다고 했는데 어떤 방법이 있는지 알아보겠습니다. 

 

 

1.  NSLayoutConstraint

NSLayoutConstraint는 제약 기반의 레이아웃 시스템에서 충족해야 하는 두 인터페이스 개체 간의 관계 입니다.

NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
item: 제약을 지정할 UI
attribute: 제약을 지정할 UI의 제약 속성
relatedBy: 제약을 지정할 UI와 제약의 기준이 되는 UI 사이의 관계
toItem: 제약의 기준이 되는 UI
attribute: 제약의 기준이 되는 UI의 제약 속성
multiplier: 제약의 비율
constraint: 제약의 상수값

 

 

2. NSLayoutAnchor

NSLayoutAnchor는 쉬운 API 사용으로 레이아웃 제약 객체를 생성하기 위한 클래스 입니다.

 

공식문서에서는 NSLayoutAnchor 클래스를 사용하면 NSLayoutConstraint API를 직접쩍으로 쓰는 것보다 몇 가지 이점이 있다고한다.

 

  • 코드가 더 clean해지고, 더 간결해지고, 더 읽기 쉬어진다.
  • NSLayoutConstraint.Attribute 서브 클래스는 추가적으로 Type 검사를 제공하여 유효하지 않은 제약 조건을 생성하는 것을 방지한다.

 

두번째 방법으로 화면을 구성해 보겠습니다.

 

먼저 화면을 구성할 UIView 파일을 만들어 줍니다. 

 

AutoLayoutView.swift

import UIKit

class AutoLayoutView: UIView {
    /*
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
     }
     */
    let titleLabel: UILabel = {
        let label = UILabel()
        
        label.text = "AutoLayout 만들기👋"
        label.textColor = .black
        label.font = .systemFont(ofSize: 24)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        
        label.text = "FirstViewController"
        label.textColor = .gray
        label.font = .systemFont(ofSize: 15)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let moveButton: UIButton = {
       let button = UIButton()
        
        button.setTitle("이동하기", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.backgroundColor = .orange
        button.contentEdgeInsets = UIEdgeInsets(top: 15,left: 20,bottom: 15,right: 20)
        button.layer.cornerRadius = 20
        button.translatesAutoresizingMaskIntoConstraints = false
      
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // Setup
        self.backgroundColor = .white
        self.addSubview(titleLabel)
        self.addSubview(descriptionLabel)
        self.addSubview(moveButton)
        
        NSLayoutConstraint.activate([
            self.titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            self.titleLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor),
            
            self.descriptionLabel.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 10),
            self.descriptionLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            
            self.moveButton.topAnchor.constraint(equalTo: self.descriptionLabel.bottomAnchor, constant: 100),
            self.moveButton.centerXAnchor.constraint(equalTo: self.centerXAnchor)
        ])
        
        //        self.descriptionLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        //        self.descriptionLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor)
        // Bind constraints
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

그리고 ViewController에서 생성해줍니다. 

 

ViewController.swift

 

import UIKit

class ViewController: UIViewController {
    
    private lazy var autoLayoutView = AutoLayoutView(frame: self.view.frame)
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view = autoLayoutView
    }
    
}