swift Custom UI - 코드로 TabBar&Navigation Controller 만들기
완성된 화면
스토리보드
첫번째 TabBarController + Navigation Controller 코드
ViewController.swift
[0]라벨 생성
[1]네비게이션 바 타이틀 초기화 (호출)
[2]네비게이션바 타이틀 초기화 2 (호출)
[3]네비게이션 바 타이틀 이미지 초기화 3 (호출)
[4]네비게이션 바 텍스트 필드 4 (호출)
[5]네비게이션 바 타이틀 구현 메서드 (함수)
[6]네비게이션바에 이미지 넣기 (함수)
[7]네비게이션 바 텍스트 필드 (함수)
// 1. 탭 바 커스터마이징 - (탭 바 이미지, 색상 커스터마이징)
// 2. 내비게이션 바 커스터마이징 (타이틀 커스터마이징)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let title = UILabel(frame: CGRect(x: 0, y: 100, width: 100, height: 30))
title.text = "첫번째 탭"
title.textColor = .red
title.textAlignment = .center
title.font = UIFont.boldSystemFont(ofSize: 14)
title.sizeToFit() //콘텐츠의 내용에 맞게 레이블 크기 변경
/*
sizeToFit()는 콘텐츠의 길이에 맞춰 레이블의 크기를 조절해 주는 메서드입니다.
이 메서드의 호출이 없으면 레이블의 너비를 넘는 콘텐츠는 엘립시스가 발생합니다.
*/
title.center.x = self.view.frame.width / 2
self.view.addSubview(title)
//탭바 이미지 타이틀 등록 - appDelegate 로 이동
//self.tabBarItem.image = UIImage(named: "calendar")
//self.tabBarItem.title = "Calendar"
//MARK: [1]네비게이션 바 타이틀 초기화
//self.initTitle()
//MARK: [2]네비게이션바 타이틀 초기화 2
//self.initTitleNew()
//MARK: [3] 네비게이션 바 타이틀 이미지 초기화 3
//self.initTitleImage()
//MARK: [4]네비게이션 바 텍스트 필드 4
self.initTextInput()
}
//MARK: 네비게이션 바 타이틀 구현 메서드
func initTitle() {
let nTitle = UILabel()
nTitle.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
nTitle.numberOfLines = 2
nTitle.textAlignment = .center
nTitle.font = UIFont.systemFont(ofSize: 15)
nTitle.text = "58개 숙소 \n 1박(1월~10일 ~ 1월 11일)"
nTitle.textColor = .white
//배경 생상 설정
let color = UIColor(red: 0.02, green: 0.22, blue: 0.49, alpha: 1.0 )
self.navigationController?.navigationBar.barTintColor = color
//titleView 속성은 뷰 기반으로 타이틀을 사용할 수 있음
self.navigationItem.titleView = nTitle
}
//MARK: 네비게이션 바 타이틀 구현 메서드 2
func initTitleNew() {
//레이아웃을 구현할 컨테이너 뷰
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
//상단 레이블
let topTitle = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 18))
topTitle.numberOfLines = 1
topTitle.textAlignment = .center
topTitle.font = UIFont.systemFont(ofSize: 15)
topTitle.text = "58개 숙소"
topTitle.textColor = .white
//하단 레이블
let subTitle = UILabel(frame: CGRect(x: 0, y: 18, width: 200, height: 18))
subTitle.numberOfLines = 1
subTitle.textAlignment = .center
subTitle.font = UIFont.systemFont(ofSize: 12)
subTitle.text = "1박(1월~10일 ~ 1월 11일)"
subTitle.textColor = .white
//레이블을 컨테이너 뷰에 추가
containerView.addSubview(topTitle)
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
}
//MARK: 네비게이션바에 이미지 넣기
func initTitleImage() {
let img = UIImage(named: "swift_logo")
let imageV = UIImageView(image: img)
self.navigationItem.titleView = imageV
}
//MARK: 네비게이션 바 텍스트 필드
func initTextInput(){
//가운데 검색 영역
let tf = UITextField()
tf.frame = CGRect(x: 0, y: 0, width: 200, height: 35)
tf.backgroundColor = .white
tf.font = UIFont.systemFont(ofSize: 13)
tf.autocorrectionType = .no
tf.autocapitalizationType = .none
tf.spellCheckingType = .no
tf.keyboardType = .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
//MARK: 왼쪽 아이템 영역
let back = UIImage(named: "arrow-back")
let leftItem = UIBarButtonItem(image: back, style: .plain, target: self, action: nil)
self.navigationItem.leftBarButtonItem = leftItem
//MARK: 오른쪽 아이템 정의
let cnt = UILabel()
cnt.frame = CGRect(x: 10, y: 8, width: 20, height: 20)
cnt.font = UIFont.systemFont(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
//카운트 뷰
let rightItem = UIBarButtonItem(customView: cnt)
//더보기 버튼 뷰
let more = UIButton(type: .system)
more.frame = CGRect(x: 50, y: 10, width: 16, height: 16)
more.setImage(UIImage(named: "more"), for: .normal)
let rightItem2 = UIBarButtonItem(customView: more)
//rightBarButtonItems는 바 버튼 아이템을 배열로 받습니다.
self.navigationItem.rightBarButtonItems = [rightItem2 , rightItem]
}
}
TabBarViewController 두번째 화면
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let title = UILabel(frame: CGRect(x: 0, y: 100, width: 100, height: 30))
title.text = "두 번째 탭"
title.textColor = .red
title.textAlignment = .center
title.font = UIFont.boldSystemFont(ofSize: 14)
title.sizeToFit() // 콘텐츠의 내용에 맞게 레이블 크기 변경
title.center.x = self.view.frame.width / 2 // 수평 중앙에 위치
self.view.addSubview(title)
// 이미지 / 타이틀 등록
//self.tabBarItem.image = UIImage(named: "file-tree")
//self.tabBarItem.title = "File"
}
}
TabBarViewController 세번째 화면
ThridViewController.swift
//
// ThridViewController.swift
// TapBar1
//
// Created by k on 2021/03/23.
//
import UIKit
class ThridViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let title = UILabel(frame: CGRect(x: 0, y: 100, width: 100, height: 30))
title.text = "세 번째 탭"
title.textColor = .red
title.textAlignment = .center
title.font = UIFont.boldSystemFont(ofSize: 14)
title.sizeToFit() // 콘텐츠의 내용에 맞게 레이블 크기 변경
title.center.x = self.view.frame.width / 2 // 수평 중앙에 위치
self.view.addSubview(title)
// 이미지 / 타이틀 등록
//self.tabBarItem.image = UIImage(named: "photo")
//self.tabBarItem.title = "Photo"
}
}
TabBarViewController 코드로 구현하기
AppDelegate.swift
[1] 탭 바 컨트롤러 생성 - 코드로 생성
[2] 윈도우 객체에 연결된 루트뷰 컨트롤러를 읽어와 UITabBarController 로 캐스팅
[3] 탭바 선택했을때 표시. 탭 바 아이템을 순회 하면서 selectedImage 속성에 이미지를 설정
[4] 탭 바 아이템에 타이틀을 설정
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
/*
//MARK: 탭 바 컨트롤러 생성 - 코드로 생성
//
let tbC = UITabBarController()
tbC.view.backgroundColor = .white
//MARK: tbC를 루트 뷰 컨트롤러로 연결
self.window?.rootViewController = tbC
//MARK: 각 탭 바 아이템에 연결된 뷰 컨트롤러 객체를 생성
let view01 = ViewController()
let view02 = SecondViewController()
let view03 = ThridViewController()
//MARK: 생성된 뷰 컨트롤러 객체에게 탭 바 컨트롤러를 등록
tbC.setViewControllers([view01, view02, view03], animated: false)
//MARK: 개별 탭 바 아이템의 속성을 설정
view01.tabBarItem = UITabBarItem(title: "Calendar", image: UIImage(named: "calendar"), selectedImage: nil)
view02.tabBarItem = UITabBarItem(title: "File", image: UIImage(named: "file-tree"), selectedImage: nil)
view03.tabBarItem = UITabBarItem(title: "Photo", image: UIImage(named: "photo"), selectedImage: nil)
*/
//MARK: 윈도우 객체에 연결된 루트뷰 컨트롤러를 읽어와 UITabBarController 로 캐스팅
if let tbc = self.window?.rootViewController as? UITabBarController {
//MARK: 탭 바로부터 탭 바 아이템 배열을 가져옴
if let tbItems = tbc.tabBar.items {
//탭 바 아이템에 이미지 등록
tbItems[0].image = UIImage(named: "designbump")?.withRenderingMode(.alwaysOriginal)
tbItems[1].image = UIImage(named: "rss")?.withRenderingMode(.alwaysOriginal)
tbItems[2].image = UIImage(named: "facebook")?.withRenderingMode(.alwaysOriginal)
//MARK: 탭바 선택했을때 표시
//탭 바 아이템을 순회 하면서 selectedImage 속성에 이미지를 설정
for tbItem in tbItems{
let image = UIImage(named: "checkmark")?.withRenderingMode(.alwaysOriginal)
tbItem.selectedImage = image
tbItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.red], for: .selected)
tbItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white], for: .disabled)
tbItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], for: .normal)
}
//MARK: 탭 바 아이템에 타이틀을 설정
tbItems[0].title = "calendar"
tbItems[1].title = "file"
tbItems[2].title = "photo"
}
//활성화된 탭 바 아이템의 이미지 색상을 변경
tbc.tabBar.tintColor = .white
//탭 바에 배경 이미지를 설정
tbc.tabBar.backgroundImage = UIImage(named: "menubar-bg-mini")
}
return true
}
// MARK: UISceneSession Lifecycle
}
참고
blog.naver.com/go4693/221371798642
'아이폰 개발 > Swift' 카테고리의 다른 글
swift get post 호출 예제 (0) | 2021.03.24 |
---|---|
swift keyChain 예제 (0) | 2021.03.23 |
swift Custom UI - 코드로 UI 만들기&데이터 전달 (0) | 2021.03.23 |
[스탠포드]Swift 강좌 - MVC 패턴 (0) | 2021.03.09 |
[스탠포드]Swift 강좌 - ios 구조 (0) | 2021.03.09 |