본문 바로가기
ios 뽀개기/실전

커스텀 내비게이션 바

by 인생여희 2018. 1. 3.
반응형

커스텀 내비게이션 바



//

//  AppDelegate.swift

//  NavCustom

//

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

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

//


import UIKit

import CoreData


@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {


    var window: UIWindow?



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

        // Override point for customization after application launch.

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

        // Saves changes in the application's managed object context before the application terminates.

        self.saveContext()

    }


    // MARK: - Core Data stack


    lazy var persistentContainer: NSPersistentContainer = {

        /*

         The persistent container for the application. This implementation

         creates and returns a container, having loaded the store for the

         application to it. This property is optional since there are legitimate

         error conditions that could cause the creation of the store to fail.

        */

        let container = NSPersistentContainer(name: "NavCustom")

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in

            if let error = error as NSError? {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                 

                /*

                 Typical reasons for an error here include:

                 * The parent directory does not exist, cannot be created, or disallows writing.

                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.

                 * The device is out of space.

                 * The store could not be migrated to the current model version.

                 Check the error message to determine what the actual problem was.

                 */

                fatalError("Unresolved error \(error), \(error.userInfo)")

            }

        })

        return container

    }()


    // MARK: - Core Data Saving support


    func saveContext () {

        let context = persistentContainer.viewContext

        if context.hasChanges {

            do {

                try context.save()

            } catch {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                let nserror = error as NSError

                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")

            }

        }

    }


}





//

//  ViewController.swift

//  NavCustom

//

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

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

//

// 내비게이션 바는 내비게이션 컨트롤러 아래에 있다 (내비게이션 바는 모든 뷰 컨트롤러에 공통으로 적용된다.)

// 내비게이션 아이템은 개별적인 뷰 컨트롤러의 통제를 받는다.(각각의 뷰 컨트롤러 마다 독립적이다.)

// 내비게이션 바는 내비게이션 컨트롤러에 속한 객체이며, 내비게이션 아이템은 뷰 컨트롤러에 속한 객체이다.

// 그래서 내비게이션 아이템을 화면에 추가할 때에는 내비게이션 컨트롤러가 아니라 뷰 컨트롤러에 추가해야 한다. 참조할때도 역시 뷰 컨트롤러를 거쳐야 한다.

// 코코아 터치 프래임 워크는 titleView를 제공한다. 타입은 UIView (뷰를 상속받은 레이블이나 버튼, 이미지 뷰를 제약 없이 타이틀에 표현 가능하다.)

import UIKit


class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        //initTitle()

        //initTitleNew()

        //imag()

        initTitleInput()

        

        //일반적인 네비게이션 바 버튼 커스텀

        //let item = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(navItem))

        //self.navigationItem.leftBarButtonItem = item

    }


    //@objc func navItem(){

    //print("버튼이 눌렸어요")

    //}

    

    

    //1. - 레이블 객체를 이용해서 표현

    func initTitle(){

        let nTitle = UILabel(frame: CGRect(x:0, y:0, width: 200, height: 40))

        nTitle.numberOfLines = 2 //줄 수

        nTitle.textAlignment = .center  // 정렬

        nTitle.textColor = UIColor.white

        nTitle.font = UIFont.systemFont(ofSize: 15) //font 사이즈

        nTitle.text = "58개 숙소 \n 1박(1월 10일 ~ 1월 11일)"

        

        self.navigationItem.titleView = nTitle

    

        //배경색상 설정

        let color = UIColor(red:0.02, green:0.22, blue:0.49, alpha:1.0)

        self.navigationController?.navigationBar.barTintColor = color

    }


    

    //2. - 컨테이너 뷰 객체에 레이블 객체를 넣어서 표현

    func initTitleNew(){

        //복합적인 레이아웃을 구현할 컨테이너 뷰

        let containerView = UIView(frame:CGRect(x:0, y:0, width:200, height:36))

        

        //상단 레이블 설정

        let nTitle = UILabel(frame: CGRect(x:0, y:0, width: 200, height: 18))

        nTitle.numberOfLines = 1 //줄 수

        nTitle.textAlignment = .center  // 정렬

        nTitle.textColor = UIColor.white

        nTitle.font = UIFont.systemFont(ofSize: 15) //font 사이즈

        nTitle.text = "58개 숙소"

        

        //하단 레이블 설정

        let subTitle = UILabel(frame: CGRect(x:0, y:18, width: 200, height: 18))

        subTitle.numberOfLines = 1 //줄 수

        subTitle.textAlignment = .center  // 정렬

        subTitle.textColor = UIColor.white

        subTitle.font = UIFont.systemFont(ofSize: 12) //font 사이즈

        subTitle.text = "1박(1월 10일 ~ 1월 11일)"

        

        

        // 상하단 레이블을 컨테이너 뷰에 추가한다.

        containerView.addSubview(nTitle)

        containerView.addSubview(subTitle)

        

        //내비게이션 타이틀에 컨테이너 뷰를 넣는다.

        self.navigationItem.titleView = containerView

        

        //배경색상 설정

        let color = UIColor(red:0.02, green:0.22, blue:0.49, alpha:1.0)

        self.navigationController?.navigationBar.barTintColor = color

    }

    

    // 3.- 이미지를 이용해서 표현

    func imag(){

        let image = UIImage(named: "swift_logo")

        let imageV = UIImageView(image: image)

        self.navigationItem.titleView = imageV

    }

    

    //4. - 텍스트 필드를 이용해서 타이틀 초기화

    func initTitleInput(){

        

        //스텝.1

        let tf = UITextField()

        tf.frame = CGRect(x:0 ,y:0,width:300, height:35)

        tf.backgroundColor = UIColor.white

        tf.font = UIFont.systemFont(ofSize: 13)

        tf.autocapitalizationType = .none //자동 대문자 변환 속성 사용하지 않기

        tf.autocorrectionType = .no //자동 입력기능 해제

        tf.spellCheckingType = .no // 스펠링 체크 해제

        tf.keyboardType = .URL // URL 입력 전용 키보드

        tf.keyboardAppearance = .dark

        tf.layer.borderWidth = 0.3 //테두리 경계선 두깨

        tf.layer.borderColor = UIColor(red: 0.60, green: 0.60, blue: 0.60, alpha: 1.0).cgColor

        

        // 타이틀 뷰 속성에 대입

        self.navigationItem.titleView = tf

        

        //스텝.2

        //왼쪽 이미지 버튼

        let back = UIImage(named: "arrow-back")

        let leftItem = UIBarButtonItem(image: back, style: .plain, target: self, action: nil)

        self.navigationItem.leftBarButtonItem = leftItem

        

        //스텝.3

        //오른쪽 버튼은 컨테이너 뷰를 만들어서 레이블과 버튼을 뷰에 넣어주면서 추가

        let rv = UIView()

        //뷰와 뷰를 상속받는 모든 객체는 위치와 크기를 지정해 줘야 한다.

        rv.frame = CGRect(x:0, y:0, width: 70, height: 37)

        

        //내비게이션 바 버튼 아이템 매개변수로 위에서 만들었던 컨테이너 뷰를 넣어주었다.

        let rItem = UIBarButtonItem(customView: rv)

        self.navigationItem.rightBarButtonItem = rItem

        

        let cnt = UILabel()

        cnt.frame = CGRect(x:10, y:8, width: 20, height: 20)

        cnt.font = UIFont.boldSystemFont(ofSize: 10)

        cnt.textColor = UIColor(red: 0.60, green: 0.60, blue: 0.60, alpha: 1.0)

        cnt.text = "12"

        cnt.textAlignment = . center

        

        //외곽선

        cnt.layer.cornerRadius = 3

        cnt.layer.borderWidth = 2

        cnt.layer.borderColor = UIColor(red: 0.60, green: 0.60, blue: 0.60, alpha: 1.0).cgColor

        

        //레이블을 서브 뷰로 추가 하기

        rv.addSubview(cnt)

        

        

        //스텝.4

        let more = UIButton(type:.system)

        more.frame = CGRect(x:50, y:10, width: 16, height: 16)

        more.setImage(UIImage(named:"more"), for: .normal)

        rv.addSubview(more)

    }

    


    

}





반응형

'ios 뽀개기 > 실전' 카테고리의 다른 글

alert 커스텀 - 기본  (0) 2018.01.03
메모장 - 커스텀(x)  (0) 2018.01.03
탭바 커스텀하기  (0) 2018.01.02
커스텀 버튼 및 데이터 전달하기  (0) 2018.01.02
커스터마이징 버튼  (0) 2017.12.27

댓글