100 days of Swift - Day 34(HTMLString, add Tabbar in code)

sun02·2021년 9월 24일
0

100 days of Swift 

목록 보기
28/40

웹의 복잡한 콘텐츠를 렌더링하는 가장 쉬운 방법은 거의 항상 WKWebView를 사용하는 것이다.


import UIKit
import WebKit

class DetailViewController: UIViewController {
	var webView: WKWebView!
    var detailItem: Petition?
    
    override func loadView() {
    	webView = WKWebView()
        view = webView
    }

그러나 petition 첵스트를 웹 뷰에 바로 넣으면 작게 보일 것이기 때문에 HTML로 래핑해야한다.


guard let detailItem = detailItem else { return }

let html = """
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style> body { font-size: 150%; } </style>
</head>
<body>
\(detailItem.body>
</body>
</html>
"""

webView.loadHTMLString(html, baseURL: nil)

HTML은 width는 기기의 width와 같고, 폰트 사이즈는 기본 폰트 사이즈의 150%로 지정한다.
모든 HTML은 청원의 본문값과 결합된 후에 webView로 전송된다.

  • guard let detailItem = detailItem else { return } : detailItem이 값을 가지면 언래핑하고 데이터가 없는 경우 메서드를 종료하게끔 한다.
  • let html : 페이지를 표시하는 데 필요한 모든 것을 포함하는 html이라는 스위프트 문자열이 있고, webView의 loadHTMLString() 메서드에 전달되어 로드된다.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
   return true
}

SceneDelegate.swift 파일의 아래 메서드에 다음과 같이 추가해준다.


var window: UIWindow?

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
 
 	guard let _ = (scene as? UIWindowScene) else { return }

        if let tabBarController = window?.rootViewController as? UITabBarController {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(identifier: "NavController")
            vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
            tabBarController.viewControllers?.append(vc)
        }
    }

  • storyboard는 뷰 컨트롤러가 보여지는 window를 자동으로 생성한다. 이 window는 initial View controller가 무엇인지 알아야하고, 이것은 rootViewController의 속성으로 설정된다.
  • single View App에서 rootViewController는 ViewController이지만 navigationController를 임베드 한 다음 네비게이션 컨트롤러를 tabbar controller에 임베드시켰기 때문에 rootViewController는 UITabBarController이다.
  • 새로운 ViewController를 만들기 위해 Main.storyboard에 대한 참조를 가져와야한다.
    • UIStoryboard(name: "Main", bundle:nil) : bundle의 nil은 "현재 앱 번들 사용"을 의미한다.
    • instantiateViewController() 메서드를 사용하여 뷰 컨트롤러를 만들고, 원하는 뷰 컨트롤러의 스토리보드ID를 전달한다.
    • 새로운 viewController의 UITabBarItem 개체를 만들어 Top Rated 아이콘과 tag 1을 지정한다.
  • tabBarController.viewControllers?.append(vc) : TabbarController에 새 뷰컨트롤러 vc를 추가한다.

0개의 댓글