swift tableview 날씨 스위프트 테이블뷰 





//

//  ViewController.swift

//  WeatherTable

//

//  Created by stayfoolish on 21/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController,UITableViewDataSource  {

    var datalist: [[String:String]] = [[:]]

    

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

        return datalist.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        print("indexPath : \(indexPath)")

        print("indexPath row : \(indexPath.row)")


        var dicTemp = datalist[indexPath.row]

        print(dicTemp)

        

        cell.textLabel?.text = dicTemp["지역"]

        

        let weatherStr = dicTemp["날씨"]

        

        cell.detailTextLabel?.text = weatherStr

        

        if weatherStr == "맑음"{

            cell.imageView?.image = UIImage(named: "sunny.png")

        }else if weatherStr == "비"{

            cell.imageView?.image = UIImage(named: "rainy.png")

        }else if weatherStr == "흐림"{

            cell.imageView?.image = UIImage(named: "cloudy.png")

        }else if weatherStr == "눈"{

            cell.imageView?.image = UIImage(named: "snow.png")

        }else {

            cell.imageView?.image = UIImage(named: "blizzard.png")


        }

        

        

        return cell

    }

    


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        let dict1 = ["지역":"한국","날씨":"비"]

        let dict2 = ["지역":"일본","날씨":"맑음"]

        let dict3 = ["지역":"중국","날씨":"눈"]

        let dict4 = ["지역":"스페인","날씨":"우박"]

        let dict5 = ["지역":"미국","날씨":"흐림"]

        let dict6 = ["지역":"영국","날씨":"비"]

        let dict7 = ["지역":"프랑스","날씨":"흐림"]

        let dict8 = ["지역":"브라질","날씨":"우박"]

        let dict9 = ["지역":"스위스","날씨":"맑음"]

        let dict10 = ["지역":"덴마크","날씨":"비"]

        let dict11 = ["지역":"스웨덴","날씨":"눈"]

        let dict12 = ["지역":"네덜란드","날씨":"비"]

        let dict13 = ["지역":"크로아티아","날씨":"맑음"]

        let dict14 = ["지역":"필리핀","날씨":"맑음"]

        let dict15 = ["지역":"독일","날씨":"눈"]

        let dict16 = ["지역":"헝가리","날씨":"비"]

        let dict17 = ["지역":"벨기에","날씨":"흐림"]

        let dict18 = ["지역":"핀란드","날씨":"우박"]

        let dict19 = ["지역":"이탈리아","날씨":"맑음"]

        

        datalist = [dict1,dict2,dict3,dict4,dict5,dict6,dict7,dict8,dict9,dict10,dict11,dict12,dict13,dict14,dict15,dict16,dict17,dict18,dict19]

    }



}










swift UIImagePickerController 스위프트 이미지피커컨트롤러 사진 불러오기 



//

//  SampleData.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import Foundation


struct Sample {

    let title: String

    let description: String

    let image: String

}


struct SampleData {

    let samples = [

        Sample(title: "Photo Object Detection", description: "불러온 이미지에 사물 인식", image: "ic_photo"),

        Sample(title: "Real Time Object Detection", description: "실시간으로 카메라에 보이는 사물 인식", image: "ic_camera"),

        Sample(title: "Facial Analysis", description: "사람 얼굴로부터 나이, 성별, 감정 추측", image: "ic_emotion")

    ]

}



//

//  MainFeatureCell.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainFeatureCell: UITableViewCell {


    @IBOutlet var featureImageView: UIImageView!

    @IBOutlet var titleLabel: UILabel!

    @IBOutlet var descriptionLabel: UILabel!

   

}


//

//  MainViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    @IBOutlet var tableView: UITableView!

    

    let sampleData = SampleData()

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

        self.tableView.dataSource = self

        self.tableView.delegate = self 

        self.tableView.tableFooterView = UIView(frame: .zero)

    }

    

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = true

        

    }

    

    override func viewWillDisappear(_ animated: Bool) {

        super.viewWillDisappear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = false

    }

    

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

        return self.sampleData.samples.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "mainFeatureCell", for: indexPath) as! MainFeatureCell

        

    let sample = self.sampleData.samples[indexPath.row]

        

        cell.titleLabel.text = sample.title

        cell.descriptionLabel.text = sample.description

        cell.imageView?.image = UIImage(named: sample.image)

        return cell

    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        switch indexPath.row {

        case 0: self.performSegue(withIdentifier: "photoObjectDetection", sender: nil)

        case 1: self.performSegue(withIdentifier: "realTimeObjectDetection", sender: nil)

        case 2: self.performSegue(withIdentifier: "facialAnalysis", sender: nil)

        default:

            return

        }

    }


}


//

//  ObjectDetectinoViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 21/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ObjectDetectinoViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {


    @IBOutlet var selectedImageView: UIImageView!

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }

    

    @IBAction func addPhoto(_ sender: UIBarButtonItem) {

        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        

        let importFromAlbum = UIAlertAction(title: "앨범에서 가져오기", style: .default) { _ in

            let picker = UIImagePickerController()

            picker.delegate = self

            picker.sourceType = .savedPhotosAlbum

            picker.allowsEditing = true

            self.present(picker, animated:  true, completion: nil )

        }

        let takePhoto = UIAlertAction(title: "카메라로 찍기", style: .default) { _  in

            let picker = UIImagePickerController()

            picker.delegate = self

            picker.sourceType = .camera

            picker.cameraCaptureMode = .photo

            picker.allowsEditing = true

            self.present(picker, animated:  true, completion: nil )

        }

        let cancel = UIAlertAction(title: "취소", style: .cancel)

        

        actionSheet.addAction(importFromAlbum)

        actionSheet.addAction(takePhoto)

        actionSheet.addAction(cancel)

        

        self.present(actionSheet, animated: true, completion: nil)

        

    }

    

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        picker.dismiss(animated: true)

        if let uiImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {

            self.selectedImageView.image = uiImage

            

        }

    }

    

}







swift alertcontroller 스위프트 얼럿컨트롤러 





//

//  SampleData.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import Foundation


struct Sample {

    let title: String

    let description: String

    let image: String

}


struct SampleData {

    let samples = [

        Sample(title: "Photo Object Detection", description: "불러온 이미지에 사물 인식", image: "ic_photo"),

        Sample(title: "Real Time Object Detection", description: "실시간으로 카메라에 보이는 사물 인식", image: "ic_camera"),

        Sample(title: "Facial Analysis", description: "사람 얼굴로부터 나이, 성별, 감정 추측", image: "ic_emotion")

    ]

}


//

//  MainFeatureCell.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainFeatureCell: UITableViewCell {


    @IBOutlet var featureImageView: UIImageView!

    @IBOutlet var titleLabel: UILabel!

    @IBOutlet var descriptionLabel: UILabel!

   

}


//

//  MainViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    @IBOutlet var tableView: UITableView!

    

    let sampleData = SampleData()

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

        self.tableView.dataSource = self

        self.tableView.delegate = self 

        self.tableView.tableFooterView = UIView(frame: .zero)

    }

    

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = true

        

    }

    

    override func viewWillDisappear(_ animated: Bool) {

        super.viewWillDisappear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = false

    }

    

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

        return self.sampleData.samples.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "mainFeatureCell", for: indexPath) as! MainFeatureCell

        

    let sample = self.sampleData.samples[indexPath.row]

        

        cell.titleLabel.text = sample.title

        cell.descriptionLabel.text = sample.description

        cell.imageView?.image = UIImage(named: sample.image)

        return cell

    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        switch indexPath.row {

        case 0: self.performSegue(withIdentifier: "photoObjectDetection", sender: nil)

        case 1: self.performSegue(withIdentifier: "realTimeObjectDetection", sender: nil)

        case 2: self.performSegue(withIdentifier: "facialAnalysis", sender: nil)

        default:

            return

        }

    }


}


//

//  ObjectDetectinoViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 21/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ObjectDetectinoViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }

    

    @IBAction func addPhoto(_ sender: UIBarButtonItem) {

        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        

        let importFromAlbum = UIAlertAction(title: "앨범에서 가져오기", style: .default) { _ in

            

        }

        let takePhoto = UIAlertAction(title: "카메라로 찍기", style: .default) { _  in

            

        }

        let cancel = UIAlertAction(title: "취소", style: .cancel)

        

        actionSheet.addAction(importFromAlbum)

        actionSheet.addAction(takePhoto)

        actionSheet.addAction(cancel)

        

        self.present(actionSheet, animated: true, completion: nil)

        

    }

    

}












swift tableview didselectrowat 스위프트 테이블뷰 선택하였을 때 




//

//  MainViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    @IBOutlet var tableView: UITableView!

    

    let sampleData = SampleData()

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

        self.tableView.dataSource = self

        self.tableView.delegate = self 

        self.tableView.tableFooterView = UIView(frame: .zero)

    }

    

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = true

        

    }

    

    override func viewWillDisappear(_ animated: Bool) {

        super.viewWillDisappear(animated)

        

        self.navigationController?.navigationBar.prefersLargeTitles = false

    }

    

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

        return self.sampleData.samples.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "mainFeatureCell", for: indexPath) as! MainFeatureCell

        

    let sample = self.sampleData.samples[indexPath.row]

        

        cell.titleLabel.text = sample.title

        cell.descriptionLabel.text = sample.description

        cell.imageView?.image = UIImage(named: sample.image)

        return cell

    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        switch indexPath.row {

        case 0: self.performSegue(withIdentifier: "photoObjectDetection", sender: nil)

        case 1: self.performSegue(withIdentifier: "realTimeObjectDetection", sender: nil)

        case 2: self.performSegue(withIdentifier: "facialAnalysis", sender: nil)

        default:

            return

        }

    }


}



//

//  SampleData.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import Foundation


struct Sample {

    let title: String

    let description: String

    let image: String

}


struct SampleData {

    let samples = [

        Sample(title: "Photo Object Detection", description: "불러온 이미지에 사물 인식", image: "ic_photo"),

        Sample(title: "Real Time Object Detection", description: "실시간으로 카메라에 보이는 사물 인식", image: "ic_camera"),

        Sample(title: "Facial Analysis", description: "사람 얼굴로부터 나이, 성별, 감정 추측", image: "ic_emotion")

    ]

}




//

//  MainFeatureCell.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainFeatureCell: UITableViewCell {


    @IBOutlet var featureImageView: UIImageView!

    @IBOutlet var titleLabel: UILabel!

    @IBOutlet var descriptionLabel: UILabel!

   

}











swift tableview custom 스위프트 테이블뷰 커스텀 



//

//  MainViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController, UITableViewDataSource {


    @IBOutlet var tableView: UITableView!

    

    let sampleData = SampleData()

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

        self.tableView.dataSource = self

        self.tableView.tableFooterView = UIView(frame: .zero)

    }

    

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

        return self.sampleData.samples.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "mainFeatureCell", for: indexPath) as! MainFeatureCell

        

    let sample = self.sampleData.samples[indexPath.row]

        

        cell.titleLabel.text = sample.title

        cell.descriptionLabel.text = sample.description

        cell.imageView?.image = UIImage(named: sample.image)

        return cell

    }



}


//

//  SampleData.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import Foundation


struct Sample {

    let title: String

    let description: String

    let image: String

}


struct SampleData {

    let samples = [

        Sample(title: "Photo Object Detection", description: "불러온 이미지에 사물 인식", image: "ic_photo"),

        Sample(title: "Real Time Object Detection", description: "실시간으로 카메라에 보이는 사물 인식", image: "ic_camera"),

        Sample(title: "Facial Analysis", description: "사람 얼굴로부터 나이, 성별, 감정 추측", image: "ic_emotion")

    ]

}


//

//  MainFeatureCell.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainFeatureCell: UITableViewCell {


    @IBOutlet var featureImageView: UIImageView!

    @IBOutlet var titleLabel: UILabel!

    @IBOutlet var descriptionLabel: UILabel!

   

}


swift tableview array 스위프트 테이블뷰 







//

//  MainViewController.swift

//  TableViewAI

//

//  Created by stayfoolish on 20/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MainViewController: UIViewController, UITableViewDataSource {


    @IBOutlet var tableView: UITableView!

    

    let dataArray = ["1","2","3","4","5","6","7","8","9","10"]

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

        self.tableView.dataSource = self

    }

    

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

        return dataArray.count

    }

    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath)

        

        cell.textLabel?.text = dataArray[indexPath.row]

        

        return cell

    }



}


swift tableview 간단한 스위프트 테이블뷰 , 디테일 뷰 



//

//  ViewController.swift

//  SimpleTable

//

//  Created by stayfoolish on 15/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {

    

    @IBOutlet var tableView : UITableView!

    let dataSource: TableData = TableData()

    let delegate: TableDelegate = TableDelegate()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        self.tableView.dataSource = self.dataSource

        self.tableView.delegate = self.delegate

        

    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        guard let cell: UITableViewCell = sender as? UITableViewCell else {

            return

        }

        

        guard let index: IndexPath = self.tableView.indexPath(for: cell) else {

            return

        }

        

        guard let nextViewController: DetailViewController = segue.destination as? DetailViewController else {

            return

        }

        

        nextViewController.index = index

    }


}



//

//  TableData.swift

//  SimpleTable

//

//  Created by stayfoolish on 15/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class TableData: NSObject, UITableViewDataSource {

    

    // 섹션수

    func numberOfSections(in tableView: UITableView) -> Int {

        return 3

    }

    

    // 섹션별 로우수

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

        

        if section == 0 {

            return 1

        }

        return 15

    }

    

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

        let cell: UITableViewCell

        cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = "\(indexPath.section) - \(indexPath.row)"

        

        return cell

    }


}


//

//  TableDelegate.swift

//  SimpleTable

//

//  Created by stayfoolish on 15/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class TableDelegate: NSObject, UITableViewDelegate {

    

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("did select \(indexPath)")

    }


}



//

//  DetailViewController.swift

//  SimpleTable

//

//  Created by stayfoolish on 15/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class DetailViewController: UIViewController {


    @IBOutlet var label: UILabel!

    var index: IndexPath!

    

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

        self.label.text = "\(self.index.description)"

    }

    


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destination.

        // Pass the selected object to the new view controller.

    }

    */


}












swift tableview 간단한 테이블뷰 추가, 삭제 스위프트







//

//  EmojiTableViewController.swift

//  Chapter08-APITest

//

//  Created by stayfoolish24 on 13/11/2018.

//


import UIKit


class EmojiTableViewController: UITableViewController {


    var emojiArtDocuments = ["One","Two","Three"]

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Uncomment the following line to preserve selection between presentations

        // self.clearsSelectionOnViewWillAppear = false


        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.

        // self.navigationItem.rightBarButtonItem = self.editButtonItem

    }


    // MARK: - Table view data source


    override func numberOfSections(in tableView: UITableView) -> Int {

        // #warning Incomplete implementation, return the number of sections

        return 1

    }


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

        // #warning Incomplete implementation, return the number of rows

        return emojiArtDocuments.count

    }


    

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "DocumentCell", for: indexPath)


        // Configure the cell...


        cell.textLabel?.text = emojiArtDocuments[indexPath.row]

        

        return cell

    }

    

    @IBAction func newEmojiArt(_ sender: UIBarButtonItem) {

        emojiArtDocuments += ["Untitled"]

        tableView.reloadData()

    }

    

    /*

    // Override to support conditional editing of the table view.

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

        // Return false if you do not want the specified item to be editable.

        return true

    }

    */


    

    // Override to support editing the table view.

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {

            // Delete the row from the data source

            emojiArtDocuments.remove(at: indexPath.row)

            tableView.deleteRows(at: [indexPath], with: .fade)

        } else if editingStyle == .insert {

            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

        }    

    }

    


    /*

    // Override to support rearranging the table view.

    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {


    }

    */


    /*

    // Override to support conditional rearranging of the table view.

    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {

        // Return false if you do not want the item to be re-orderable.

        return true

    }

    */


    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destination.

        // Pass the selected object to the new view controller.

    }

    */


}


MyWebBrowser swift 스위프트 웹브라우저 앱 



//

//  ViewController.swift

//  MyWebBrowser

//

//  Created by stayfoolish on 07/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import WebKit


class ViewController: UIViewController {

    

    // MARK: - Properties

    // MARK: IBOutlets

    @IBOutlet var webView: WKWebView!

    @IBOutlet var activityIndicator: UIActivityIndicatorView!

    

    // MARK: - Methods

    // MARK: Life Cycle

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        self.webView.navigationDelegate = self

    }


    override func viewDidAppear(_ animated: Bool) {

        super.viewDidAppear(animated)

        

        let firstPageURL: URL?

        

        if let lastURL: URL = UserDefaults.standard.url(forKey: lastPageURLDefaultKey){

            firstPageURL = lastURL

        }else {

            firstPageURL = URL(string: "https://www.google.com")

        }

        

        guard let pageURL: URL = firstPageURL else {

            return

        }

        

        let urlRequest: URLRequest = URLRequest(url: pageURL)

        self.webView.load(urlRequest)

    }

    

    // MARK: IBActions

    @IBAction func goBack(_ sender: UIBarButtonItem){

        self.webView.goBack()

    }

    

    @IBAction func goForward(_ sender: UIBarButtonItem){

        self.webView.goForward()

    }


    @IBAction func refresh(_ sender: UIBarButtonItem){

        self.webView.reload()

    }

    

    

    // MARK: Custom Methods

    func showNetworkingIndicators(){

        self.activityIndicator.isHidden = false

        self.activityIndicator.startAnimating()

        UIApplication.shared.isNetworkActivityIndicatorVisible = true

    }

    

    func hideNetworkingIndicators(){

        self.activityIndicator.isHidden = true

        self.activityIndicator.startAnimating()

        UIApplication.shared.isNetworkActivityIndicatorVisible = false

    }

}


extension ViewController: WKNavigationDelegate {

    

    //MARK: WKNavigationsDelegate

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){

        print("did finish navigation")

        

        if let appDelegate: AppDelegate = UIApplication.shared.delegate as? AppDelegate {

            appDelegate.lastPageURL = webView.url

        }

        

        webView.evaluateJavaScript("document.title") { (value: Any?, error: Error?) in

            if let error: Error = error {

                print(error.localizedDescription)

                return

            }

            

            guard let title: String = value as? String else {

                return

            }

            

            self.navigationItem.title = title

        }

        self.hideNetworkingIndicators()

}

    

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation! , withError error: Error){

        print("did fail navigation")

        print("\(error.localizedDescription)")

        

        self.hideNetworkingIndicators()

        let message: String = "오류발생!\n" + error.localizedDescription

        

        let alert: UIAlertController

        alert = UIAlertController(title: "알림", message: message, preferredStyle: UIAlertController.Style.alert)

        

        let okayAction: UIAlertAction

        okayAction = UIAlertAction(title: "확인", style: UIAlertAction.Style.cancel, handler: nil)

        

        alert.addAction(okayAction)

        

        self.present(alert, animated: true, completion: nil)

    }

    

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){

        print("did start navigation")

        self.showNetworkingIndicators()

    }


}




//

//  AppDelegate.swift

//  MyWebBrowser

//

//  Created by stayfoolish on 07/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


// 마지막 페이지 주소를 UserDefaults에서 관리하기 위한 키 값

let lastPageURLDefaultKey: String = "lastURL"


@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {


    

    

    

    // MARK: - Prperties

    var window: UIWindow?

    var lastPageURL: URL?


    // MARK: - Methods

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

        // Override point for customization after application launch.

        

        self.lastPageURL = UserDefaults.standard.url(forKey: lastPageURLDefaultKey   )

        return true

    }


    func applicationWillResignActive(_ application: UIApplication) {

        let userDefaults: UserDefaults

        userDefaults = UserDefaults.standard

        

        userDefaults.set(self.lastPageURL, forKey: lastPageURLDefaultKey)

        userDefaults.synchronize()

    }


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

    }



}






 스위프트 화면 전환 present dismiss push pop segue modal swift






//

//  ViewController.swift

//  PresentScreen

//

//  Created by stayfoolish on 06/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class ViewController: UIViewController {


    @IBOutlet var nameTextField: UITextField!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    @IBAction func presentMenuClicked(_ sender: UIButton) {

        if let menuScreen = self.storyboard?.instantiateViewController(withIdentifier: "Menu"){

            menuScreen.modalTransitionStyle = .coverVertical

            self.present(menuScreen, animated: true, completion: nil)

        }


    }

    

    @IBAction func moveToMenuClicked(_ sender: UIBarButtonItem) {

        

        if let menuScreen =  self.storyboard?.instantiateViewController(withIdentifier: "Menu"){

            self.navigationController?.pushViewController(menuScreen, animated: true)

        }

    }

    

    @IBAction func manualMenuClicked(_ sender: UIButton) {

        self.performSegue(withIdentifier: "ManualMenu", sender: self)

    }

    

    @IBAction func unwindFromMenu(segue: UIStoryboardSegue){

        NSLog("unwindFromMenu 호출됨")

    }

    

    @IBAction func menuClicked(_ sender: UIButton) {

         let menuScreen = storyboard!.instantiateViewController(withIdentifier: "Menu") as? MenuViewController

        navigationController?.pushViewController(menuScreen!, animated: true)

        menuScreen?.paramData = self.nameTextField.text!

    }

    

    

}




//

//  MenuViewController.swift

//  PresentScreen

//

//  Created by stayfoolish on 06/11/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit


class MenuViewController: UIViewController {


    @IBOutlet var nameLabel: UILabel!

    

    var paramData = ""

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view.j

        nameLabel.text = paramData

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }


    @IBAction func backClicked(_ sender: UIButton) {

       self.presentingViewController?.dismiss(animated: true, completion: nil)

    }

    @IBAction func backClickedPop(_ sender: UIButton) {

        self.navigationController?.popViewController(animated: true)

    }

    /*

    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        // Get the new view controller using segue.destination.

        // Pass the selected object to the new view controller.

    }

    */


}




+ Recent posts