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

간단한 tableview - 스토리보드 없이 코드로만 만들어보기 tableview 커스터마이징

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

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



소스코드 첨부

TableViewCode.zip





AppDelegate.swift

//

//  AppDelegate.swift

//  TableViewCode

//

//  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()

        window?.rootViewController = UINavigationController(rootViewController: MessageController())

        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:.

    }



}


MessageController.swift

//

//  MessageController.swift

//  TableViewCode

//

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

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

//


import UIKit


class MessageController: UITableViewController {


    var users = [User]()

    

    let cellId = "Cell"

    

    override func viewDidLoad() {

        super.viewDidLoad()

        //밑에서 만든 테이블 뷰 cell 클래스를 등록시켜주기

        tableView.register(UserCell.self, forCellReuseIdentifier: cellId)

        

        tableView.backgroundColor = .white

        //데이터 넣어주기

        let usera = User(image: "a.jpg", name: "홍길동", message: "밥먹었어?")

        let userb = User(image: "b.jpg", name: "박미선", message: "하이루?")

        let userc = User(image: "c.jpg", name: "강호동강호동강호동강호동강호동강호동강호동강호동강호동", message: "행님아~!~~~~~~~~~~~~~~~~~~~~?")

        users.append(usera)

        users.append(userb)

        users.append(userc)

        

    }



    //테이블 뷰 셀 개수

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return users.count

    }


    //테이블 뷰 셀을 구성하는 함수

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell

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

        cell.myLableOne.text = users[indexPath.row].name

        cell.myLableTwo.text = users[indexPath.row].message

        return cell

    }

    

    //테이블 높이 설정

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 80

    }



}




//테이블 뷰 셀 커스터 마이징 하기

class UserCell: UITableViewCell {

    

    

    //이미지 뷰

    let myImage: UIImageView = {

    

    let img = UIImageView()

    img.translatesAutoresizingMaskIntoConstraints = false

    img.backgroundColor = .yellow

    img.layer.cornerRadius = 24

    img.layer.masksToBounds = true

   // img.contentMode = .scaleAspectFit

    return img

    }()

    //라벨 1

    let myLableOne : UILabel = {

        let lbo = UILabel()

        //lbo.text = "text1"

        lbo.translatesAutoresizingMaskIntoConstraints = false

        lbo.numberOfLines = 0

        lbo.sizeToFit()

        lbo.font = UIFont.boldSystemFont(ofSize: 14)

        //lbo.backgroundColor = .blue

        return lbo

    }()

    //라벨 2

    let myLableTwo: UILabel = {

        let lbo = UILabel()

        //lbo.text = "text2"

         lbo.numberOfLines = 0

           lbo.sizeToFit()

        lbo.translatesAutoresizingMaskIntoConstraints = false

        lbo.font = UIFont.boldSystemFont(ofSize: 12)

       //// lbo.backgroundColor = .blue

        return lbo

    }()

    

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: .default, reuseIdentifier: "Cell")

        //계층 구조도에 따라서 cell에 위에서 만든 view 객체들을 넣어주기

       addSubview(myImage)

        addSubview(myLableOne)

       addSubview(myLableTwo)

        

        setupImage()

    }

    

    //제약조건 설정해주기

    func setupImage(){

        

        myImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

        myImage.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true

        myImage.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 10)

        myImage.widthAnchor.constraint(equalToConstant: 50).isActive = true

        myImage.heightAnchor.constraint(equalToConstant: 50).isActive = true

        

        

        myLableOne.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

        myLableOne.leftAnchor.constraint(equalTo: myImage.rightAnchor, constant: 15).isActive = true

        //myLableOne.rightAnchor.constraint(equalTo: myLableTwo.leftAnchor).isActive = true

        myLableOne.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 10)

        myLableOne.widthAnchor.constraint(equalToConstant: 100).isActive = true

        myLableOne.heightAnchor.constraint(equalToConstant: 10).isActive = true

        

        

        myLableTwo.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

        //myLableTwo.leftAnchor.constraint(equalTo: myLableOne.rightAnchor, constant: 10)

        myLableTwo.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true

        myLableTwo.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 10)

        myLableTwo.widthAnchor.constraint(equalToConstant: 100).isActive = true

        myLableTwo.heightAnchor.constraint(equalToConstant: 10).isActive = true

        

    }


    

    required init?(coder aDecoder: NSCoder) {

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

    }}


user.swift

import Foundation


class User{

    

    var image: String!

    var name: String!

    var message: String!

    

    init(image:String,name:String,message:String) {

        

        self.image = image

        self.name = name

        self.message = message

    }

    }




반응형

댓글