
おそらく使用頻度が高いであろう便利なメソッドをココに書き溜めておきます!
画像関連
fa-chevron-circle-right画像を差し替えたいときに使う
1 |
XXX.image = UIImage(named: "YYY") |
fa-chevron-circle-rightアルバムの使用許可を求める
1 2 3 4 5 6 7 8 9 10 11 12 |
PHPhotoLibrary.requestAuthorization { (status) in switch(status) { case .authorized: break case .denied: break case .notDetermined: break case .restricted: break } } |
fa-chevron-circle-rightスクリーンショットを撮る
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
func takeScreenShot() { //幅・高さを決める let width = CGFloat(UIScreen.main.bounds.size.width) let height = CGFloat(UIScreen.main.bounds.size.height) let size = CGSize(width: width, height: height) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) //viewに書き出す self.view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) XXX = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() } |
fa-chevron-circle-rightカメラを立ち上げる
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
func XXX(_ sender: Any) { //カメラを立ち上げるコード let souceType = UIImagePickerController.SourceType.camera //カメラが利用可能かチェック if UIImagePickerController.isSourceTypeAvailable(.camera) { //変数化(インスタンス化) let cameraPicker = UIImagePickerController() cameraPicker.sourceType = souceType cameraPicker.delegate = self cameraPicker.allowsEditing = true //カメラの編集を許す present(cameraPicker, animated: true, completion: nil) }else{ print("エラー") } } |
fa-chevron-circle-rightカメラモード中にキャンセルボタンが押された時にカメラを閉じる。
1 2 3 4 5 6 |
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) //カメラの画面が閉じる } |
fa-chevron-circle-right撮ったあるいはアルバムから選択された写真を受け取る(取得する)
選択・撮影完了時に呼ばれる
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//infoの中に画像が入っている func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let pickedImage = info[.editedImage] as? UIImage { backImageView.image = pickedImage //選択した写真がイメージに反映される //写真の保存 UIImageWriteToSavedPhotosAlbum(pickedImage, self, nil, nil) //カメラやアルバムを閉じる処理 picker.dismiss(animated: true, completion: nil) } |
fa-chevron-circle-right画像をシェアする時
1 2 3 4 5 6 7 8 9 10 |
@IBAction func share(_ sender: Any) { let text = "#tamariba" let image = backImageView.image?.jpegData(compressionQuality: 0.2) //写真の圧縮 let items = [text, image] as [Any] //UIActivityViewControllerのインスタンス化 let activityVC = UIActivityViewController(activityItems: items, applicationActivities: nil) present(activityVC, animated: true, completion: nil) //最後に開く } |
キーボード関連
fa-chevron-circle-rightタッチでキーボードを閉じる
1 2 3 4 |
override func touchesBegan(_ touches: Set<uitouch>, with event: UIEvent?) { view.endEditing(true) }</uitouch> |
fa-chevron-circle-rightリターンでキーボードを閉じる
1 2 3 4 5 6 |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } |
fa-chevron-circle-righttextFieldタップでキーボードを出し、画面全体が上昇→元に戻す
1 2 3 4 5 6 7 |
NotificationCenter.default.addObserver(self, selector: #selector(XXX.keyboardWillShow(_ :)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(XXX.keyboardWillHide(_ :)), name: UIResponder.keyboardWillHideNotification, object: nil) keyboardWillShow()とkeyboardWillHideは自分で作成する |
fa-chevron-circle-righttextFieldの枠線消す
1 2 3 |
// xxxTextField.borderStyle = .none |
fa-chevron-circle-rightキーボードが表示された時、その高さ分textfieldが上昇し、非表示になったら元に戻る
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@objc func keyboardWillShow(_ notification: NSNotification) { let keyboardHeight = ((notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as Any) as AnyObject).cgRectValue.height XXXTextField.frame.origin.y = screenSize.height - keyboardHeight - commentTextField.frame.height } @objc func keyboardWillHide(_ notification: NSNotification) { XXXTextField.frame.origin.y = screenSize.height - commentTextField.frame.height guard let rect = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue, let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else{return} } |
遷移関連
fa-chevron-circle-right戻る時
1 2 3 |
func a() { dismiss(animated: true, completion: nil) } |
fa-chevron-circle-right画面遷移
1 |
performSegue(withIdentifier: "XXX", sender: nil) |
fa-chevron-circle-right遷移先に値を渡す
1 2 3 4 5 6 7 8 |
func prepare(for segue: UIStoryboardSegue, sender: Any?) { let nextVC = segue.destination as! NextViewController nextVC.xxx = xxxx nextVC.yyy = yyyy } |
xxxとyyyはNextViewControllerで定義しておくこと。
fa-chevron-circle-rightビューが表示される直前(画面が表示されるたび)に何かしたい時
1 2 3 4 |
func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } |
fa-chevron-circle-rightstoryboardIDを使って画面遷移
1 |
let xxxVC = self.storyboard?.instantiateViewController(identifier: "xxxVC") as! xxxViewController |
サイズ関連
fa-chevron-circle-rightサイズを指定する
1 |
CGRect(x: , y: , width: , height: ) |
TableView関連
fa-chevron-circle-rightセルの数を決める
UITableviewの必須メソッド
1 2 3 |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return セルの数 } |
fa-chevron-circle-rightセルのセクションの数
1 2 3 |
func numberOfSections(in tableView: UITableView) -> Int { return セクションの数 } |
fa-chevron-circle-rightセルの構築
UITableviewの必須メソッド
1 2 3 |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return cell } |
fa-chevron-circle-rightセルの高さ
1 2 3 |
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return XXX } |
fa-chevron-circle-rightセルがタップされたときに呼ばれる
1 2 3 4 |
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } |
fa-chevron-circle-rightセルがサイズ変更されることを保証
1 2 3 4 5 |
func XXX(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let xxx = timeLineTableView.dequeueReusableCell(withIdentifier: "yyy", for: indexPath) } |
fa-chevron-circle-rightセルのハイライトを消す
cellForRowAtの中で
1 |
cell.selectionStyle = .none |
fa-chevron-circle-rightシンプルにそのVCでnavigationControllerを非表示
1 2 3 4 5 6 |
// override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } |
これはviewWillAppear内に書かないと効かない。
fa-chevron-circle-right戻った時にナビを隠す
1 2 3 4 5 6 |
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } |
fa-chevron-circle-right(前のVCでナビ消した際などに)現在のVCでナビを復活させる
1 2 3 4 5 6 |
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) } |
データ関連
fa-chevron-circle-rightアプリ内にデータを保存する
1 |
UserDefaults.standard.set(保存したいもの, forKey: "キー値") |
fa-chevron-circle-rightアプリ内の保存されたデータを取り出す
1 2 3 |
if UserDefaults.standard.object(forKey: キー値) != nil { 変数 = UserDefaults.standard.object(forKey: キー値) } |
タイマー
fa-chevron-circle-rightタイマーを使う
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//timer()の使い方 例 //timerクラスのインスタンス生成 var timer = Timer() //timerを起動するメソッド func startTimer() { //タイマーを回す timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true) //timeInterval: 何秒ごとに呼ぶのか //target: どこのメソッドを呼ぶか(selfならこのviewcontrollerないのメソッド) //selector: なんのメソッドを呼ぶのか(timerUpdateメソッド) // つまりこの場合、 0.5秒ごとに自身のクラスのtimerUpdateメソッドを呼ぶという意味 } //0.5秒ごとに呼ばれるtimerUpdateメソッド(頭の@objcは必須) @objc func timerUpdate() { //行いたい処理 } |