티스토리 뷰

코드를 이용해 AutoLayout을 구현해보자.

 

 

먼저 View 하나를 만들고 backgroundColor를 blue로 해주었다.

import UIKit

class ViewController: UIViewController {
    
    let firstView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        firstView.backgroundColor = .blue
    }
}

 

1. addSubview

addSubview로 firstView를 추가해주자.

view.addSubview(firstView)

 

 

2. translatesAutoresizingMaskIntoConstraints = false

firstView.translatesAutoresizingMaskIntoConstraints = false

false로 해줘야 auto layout이 적용된다. 이 옵션은 나중에 다뤄보자.

 

 

3.  Constraint

이제 firstView의 constraint를 설정해보자.

 

firstView에는 여러 constraint를 줄 수 있는데 그중에서 topAnchor, leadingAnchor, trailingAnchor 그리고 heightAnchor를 추가했다. 

NSLayoutConstraint.activate([

            firstView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
            firstView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            firstView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            firstView.heightAnchor.constraint(equalToConstant: 200)
       
])

 

 

topAnchor의 constraint를 보자.

firstView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100)

firstView의 topAnchor는 view(=superView)의 topAnchor보다 100만큼 떨어져 있다는 의미이다.

 

 

 

widthAnchor, heightAnchor는 equalToConstant를 이용해 constant만 설정 가능하다.

firstView.heightAnchor.constraint(equalToConstant: 200) // 높이를 200으로 설정

 

 

다음과 같이 잘 나온다.

 

 

 

 

 


정말 간단하게 작성해 보았다.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함