본문 바로가기
ios 뽀개기/ios 강좌

Ios AutoLayout 4 -UICollectionViewController 활용

by 인생여희 2018. 5. 5.
반응형

Ios AutoLayout 4 -UICollectionViewController 활용


● 들어가기 전

이번포스팅에서는 UICollectionViewController를 이용해서 페이지를 좌우로 넘겨주는 기능을 살펴보자.

● 실습순서

1.rootview를 UICollectionViewController를 상속받는 클래스로 지정해주기

2. UICollectionViewController를 상속받는 클래스 지정

3. UICollectionViewController의 Cell을 꾸며줄 Customcell 만들기

4.ViewController에 있던 소스 UICollectionViewController를 상속받는 클래스로 옮기기


● rootview 지정해주기

AppDelegate파일로 들어와서 window 객체를 초기화 하는 코드를 작성해준다. 각 코드에 대한 설명은 주석을 달아놓았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
       //window객체 초기화
        window = UIWindow()
        //window객체를 code로 변경시켜주도록 설정
        window?.makeKeyAndVisible()
        
        //UICollectionViewFlowLayout 컬렉션 뷰 레이아웃과 관련된 객체
        let layout = UICollectionViewFlowLayout()
        //가로로 스크롤되게 설정
        layout.scrollDirection = .horizontal
        //SwipingController 객체를 생성하고 최상위 뷰로 설정
        let swipingController = SwipingController(collectionViewLayout: layout)
        
        window?.rootViewController = swipingController
        
        return true
    }
 
cs

● UICollectionViewController를 상속받는 클래스 지정

UICollectionViewController를 상속받는 클래스를 만들어 주었다.
여기서 UICollectionViewDelegateFlowLayout 도 상속받았는데, 레이아웃을 설정해 주려면 반드시 상속받아야 하는 녀석이다. 그리고 viewDidLoad()에서 배경화면을 설정해주고, customcell을 등록시켜주었다. 그 아래에 나열되있는 함수는 UICollectionViewController를 구성해주는 함수다. 반드시 구현을 해야 한다. UICollectionViewCell을 상속받는 PageCell은 따로 만들어준다. 나머지 설명은 주석을 참고하자.
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
32
33
34
35
36
 
import UIKit
//UICollectionViewController를 상속 받는 클래스, 레이아웃과 cell의 size를 조정하려면 UICollectionViewDelegateFlowLayout을
//상속받아야 한다.
class SwipingController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //배경색을 흰색
        collectionView?.backgroundColor = .white
        //collectionView에 cell을 등록해주는 작업, 여기서는 직접 만든 cell을 넣어주었고, 아이디를 설정해 주었다.
        collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId")
        //페이징기능 허용
        collectionView?.isPagingEnabled = true
    }
    //컬렉션 뷰의 셀 사이사이마다 간격설정 원래는 디폴드 값으로 10이 지정되어 있음
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int-> CGFloat {
        return 0
    }
    //컬렉션 뷰의 cell 개수 지정.
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int-> Int {
        return 4
    }
    //컬렉션 뷰의 cell을 구성하는 함수
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //위에서 등록해준 커스텀 셀을 가져와서 리턴해줌
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId"for: indexPath)
        return cell
    }
    //커스텀 셀의 크기를 view에 꽉차게 해주었다.
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }
    
}
 
cs

● UICollectionViewCell을 상속 받는 PageCell 작성

UICollectionViewCell을 상속받는 PageCell을 만들어 주었다. 여기서 반드시 overrid init() 메소드를 호출해서 부모 인스턴스를 초기화 해줘야 한다. 그래야 커스터마이징 할 수 있다. 그리고 viewController 함수에서 이미지 객체와 텍스트 객체를 가져와서 autolayout을 설정해준다. 이때 view가 기준이 아니라 cell이 기준이 된다. 그래서 지금 cell 안에서 autolayout을 작성하고 있기 때문에 기준인 cell. 이라고 굳이 적어줄 필요는 없다. 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
 
 
import UIKit
 
class PageCell: UICollectionViewCell {
    
    //클로저 기능으로 이미지객체 만들어주기(내부에서 속성정의)
    let myImageView: UIImageView = {
        let imageView = UIImageView(image: #imageLiteral(resourceName: "mypic1"))
        // 이속성은 autolayout을 이용할 수 있게한다.
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    ////클로저 기능으로 textView객체 만들어주기(내부에서 속성정의)
    let myTextView: UITextView = {
        let textView = UITextView()
        let attributedText = NSMutableAttributedString(string: "ios기초 레슨 프로그램", attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 18)])
        
        attributedText.append(NSAttributedString(string: "\n\n\n 할아버지 할머니도, 엄마도 아빠도 쉽게 배울 수 있는 아이폰 개발 강좌~!! 모두 열공 가즈아~~~~!", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 13), NSAttributedStringKey.foregroundColor: UIColor.gray]))
        
        textView.attributedText = attributedText
        
        //textView.text = "ios기초 레슨 프로그램"
        //textView.font = UIFont.boldSystemFont(ofSize: 18)
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.textAlignment = .center
        textView.isEditable = false
        textView.isScrollEnabled = false
        return textView
    }()
 
    //부모 인스턴스를 초기화 해줘야 커스터마이징 해줄 수 있다.
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
    }
    
    private func setupLayout() {
        
        let containerView = UIView()
        containerView.backgroundColor = .yellow
        //현재 cell에 콘테이너 뷰 추가
        addSubview(containerView)
        // 오토레이아웃 활성화
        //이제 제약조건이 view 기준이 아니기 때문에 view를 빼줘야 한다.
        containerView.translatesAutoresizingMaskIntoConstraints = false
        containerView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        containerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        containerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        //부모뷰에 이미지 뷰 넣어주기
        containerView.addSubview(myImageView)
        
        
        myImageView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
        myImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        myImageView.heightAnchor.constraint(equalTo: containerView.heightAnchor, multiplier: 0.5).isActive = true
        
        //부모뷰의 높이를 view의 절반으로 맞춰줬다.
        containerView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5).isActive = true
        
        //현재 cell에 textview 추가
        addSubview(myTextView)
        //myTextView의  topAnchor를 이미지뷰 아래에 맟추고 120 만큼 간격 띄어주기
        //이제 제약조건이 view 기준이 아니기 때문에 view를 빼줘야 한다.
        myTextView.topAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 120).isActive = true
        myTextView.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
        myTextView.rightAnchor.constraint(equalTo: rightAnchor, constant: -24).isActive = true
        myTextView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
 
 
cs

● 마무리

UICollectionViewController에 대해서 알아 보았다. 이 view를 구현하려면 UICollectionViewController를 상속받고 또한 레이아웃을 설정해주기 위한 클래스 UICollectionViewDelegateFlowLayout을 상속받아야 한다. 그리고 UICollectionView를 구현해줄 메소드를 작성해줘야 한다. 반드시. 그리고 cell을 꾸며줄려면 UICollectionViewCell를 상속받는 클래스를 만들어주고 부모 인스턴스를 초기화 한다음에 사용해주면 되겠다.




반응형

댓글