본문 바로가기
ios 뽀개기/ios앱

간단한 collectionview - 스토리보드 없이 코드로만 만들어보기 (커스텀셀)

by 인생여희 2018. 2. 8.
반응형

간단한 collectionview - 스토리보드 없이 코드로만 만들어보기


소스파일 첨부


CollectionViewCode.zip



AppDelegate.swift

//

//  AppDelegate.swift

//  CollectionViewCode

//

//  Created by MacBookPro on 2018. 2. 8..

//  Copyright © 2018년 MacBookPro. All rights reserved.

//


import UIKit


@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {


    var window: UIWindow?



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        

        //스토리보드를 사용하지 않겠다.

        window = UIWindow(frame: UIScreen.main.bounds)

        window?.makeKeyAndVisible()

        

        //CollectoinView를 상속받는 HomeController에 UICollectionViewFlowLayout 설정

        let homeController = HomeController(collectionViewLayout: UICollectionViewFlowLayout())

        //최상위 뷰로 HomeController 할당

        window?.rootViewController = UINavigationController(rootViewController: homeController)

        

        return true

    }


    func applicationWillResignActive(_ application: UIApplication) {

        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

    }


    func applicationDidEnterBackground(_ application: UIApplication) {

        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    }


    func applicationWillEnterForeground(_ application: UIApplication) {

        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    }


    func applicationDidBecomeActive(_ application: UIApplication) {

        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    }


    func applicationWillTerminate(_ application: UIApplication) {

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    }



}



HomeController.swift

//

//  HomeController.swift

//  CollectionViewCode

//

//  Created by MacBookPro on 2018. 2. 8..

//  Copyright © 2018년 MacBookPro. All rights reserved.

//


import UIKit


class MyCell: UICollectionViewCell{

    //부모 메서드 초기화 시켜줘야 한다.

    override init(frame: CGRect) {

        super.init(frame: frame)

        setupView()

    }

    

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    

    //셀에 이미지 뷰 객체를 넣어주기 위해서 생성

    let myImage: UIImageView = {

        let img = UIImageView()

        //자동으로 위치 정렬 금지

        img.translatesAutoresizingMaskIntoConstraints = false

        return img

    }()

    

    func setupView(){

        backgroundColor = .yellow

        //셀에 위에서 만든 이미지 뷰 객체를 넣어준다.

        addSubview(myImage)

        //제약조건 설정하기

        myImage.topAnchor.constraint(equalTo: self.topAnchor).isActive = true

        myImage.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true

         myImage.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true

          myImage.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

        //myImage.widthAnchor.constraint(equalToConstant: 0).isActive = true

        //myImage.heightAnchor.constraint(equalToConstant: 0).isActive = true

    }

}





private let reuseIdentifier = "Cell"


//코드로 만들때는 uicollectionviewdatasource와 delegate 프로토콜을 상속 받을 필요가 없다.

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


    let images = ["a.jpg","b.jpg","c.jpg","a.jpg","b.jpg","c.jpg","a.jpg","b.jpg","c.jpg","a.jpg","b.jpg","c.jpg","a.jpg","b.jpg","c.jpg"]

    

    override func viewDidLoad() {

        super.viewDidLoad()

        collectionView?.backgroundColor = .white

        //셀 등록

        self.collectionView!.register(MyCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    //컬렉션뷰의 셀 개수

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return images.count

    }


    //셀을 구숭하는 함수

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        //셀 참조 값 가져오기

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyCell

        

        //이미지 삽입

        cell.myImage.image = UIImage(named: images[indexPath.row])

        return cell

    }


    //셀크기

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let collWidth = collectionView.frame.width / 3 - 1

        return CGSize(width: collWidth, height: collWidth)

    }

    

    //위아래 간격

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

        return 1

    }

    //좌우간격

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

        return 1

    }

}




스토리보드를 이용해서 만드는 것과 차이점은 uiimage 객체를 직접 코드로 만들어 줘야 한다는점, delegate, datasource 프로토콜 메소드를 상속받을 필요 없다는 점. 단지 셀의 사이즈를 담당하는 UICollectionViewDelegateFlowLayout=만 상속 받으면 셀의 크기를 조정하는 건 동일 하다. 또한 코드로 만들때 상속받아야되는 메소드들이 있고, 상속을 받고 부모 메서드를 초기화해줘야 한다는 점이이 있다. 복잡한 화면을 구현 할때는 코드로 만들고 간단한 화면을 구현할때는 스토리 보드로 만들면 될것 같다.



반응형

댓글