#44 present function-2-顯示 iOS SDK 內建的 controller

UIImagePickerController、PickerView、MKMapView、UIReferenceLibraryViewController、SFSafariViewController、UIColorPickerViewController

練習 iOS SDK 提供的 controller

前一篇我們研習了 present function 的使用方式

現在我們用 present 來操作 iOS 幫我們寫好的一些 Class

使用者資料設定頁

☑ 選頭像使用照片:UIImagePickerController,

☑ 選所在地:PickerView

☑ 用地圖顯示所在地:MKMapView,

☑ 點名字可以查字典:UIReferenceLibraryViewController,

☑ 點個人medium網站:SFSafariViewController,

☑ 改變背景色可以用:UIColorPickerViewController

點個人介紹影片AVPlayerViewController,

分享個人名片 UIActivityViewController,

點 email 可以寄信 MFMailComposeViewController,

UIImagePickerController

選頭像用照片 UIImagePickerController

import UIKit
class userSettingViewController: UIViewController,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate{

@IBOutlet weak var userPhotoImageView: UIImageView!

override func viewDidLoad() {
super.viewDidLoad()
userPhotoImageView.layer.cornerRadius = 60
}

@IBAction func selectProfileImage(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}

// 使用者選擇照片後的回調函數
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
userPhotoImageView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}

// 使用者取消選擇照片的回調函數
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}

PickerView

自建一個選地點的 LocationSelectionViewController,將 這個視圖控制器 present 出來,然後在使用者用 PickerView 選擇完縣市後,將選中的字串填回主視窗的 locationLabel。

MKMapView

自建一個顯示地圖的 MapViewController,將 這個視圖控制器 present 出來,然後使用 MapView 在地圖顯示使用者剛選擇的地點。

字典 UIReferenceLibraryViewController

讓使用者輸入名字,順便查一下有沒有什麼好或不好的含意,如果一開始沒安裝字典,點『管理字典』把想要的字典加上去,再重新執行就看的到字典內容了。

    @IBAction func nameReferenceLibrary(_ sender: UIButton) {
let controller = UIReferenceLibraryViewController(term: userNameTextField.text!)
present(controller, animated: true)
}

查其他語言也是OK的,只要字典有內容

SFSafariViewController

用 SFSafariViewController 顯示 medium 網址

    @IBAction func openMediumWebsite(_ sender: Any) {
let id:String = mediumIdTextField.text!
let url = URL(string: "https://medium.com/\(id)")!
print(url)
let safariViewController = SFSafariViewController(url: url)
present(safariViewController, animated: true, completion: nil)
}

UIColorPickerViewController

改變背景色可以用:UIColorPickerViewController

    @IBAction func showColorPicker(_ sender: UIButton) {
let colorPickerVC = UIColorPickerViewController()
colorPickerVC.delegate = self
present(colorPickerVC, animated: true, completion: nil)
}

// 實作 UIColorPickerViewControllerDelegate 方法
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
view.backgroundColor = viewController.selectedColor
}

--

--