LoginSignup
0
0

More than 5 years have passed since last update.

Swift3 よく使う機能の簡略まとめ

Last updated at Posted at 2018-03-12

はじめに

個人的な選別ですが
Swift3 でよく使うコードをまとめました。

UIViewControllerの雛形

Sample
//MARK: - IBAOutlet 関連付け

//MARK: - Variable  変数

//MARK: - Constant  定数

//MARK: - Life cycle
override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewDidAppear(_ animated: Bool) {

}

override func viewWillAppear(_ animated: Bool) {

}

override func viewDidDisappear(_ animated: Bool) {

}

override func viewWillDisappear(_ animated: Bool) {

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: - My Function


//MARK: - DataSource


//MARK: - Delegate

UIViewControllerでTableViewを使用する時 (xib)(WordCellという自作クラス使用)

Sample
import UIKit

class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate{

    @IBOutlet var table:UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        table.delegate = self
        table.dataSource = self

        let nib = UINib(nibName: "WordCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "WordCell")
    }

    //Table Viewのセルの数を指定 (保存している配列のcountなど)
    func tableView(_ table: UITableView, numberOfRowsInSection section: Int) -> Int {
        return num
    }

    //各セルの要素を設定する
    func tableView(_ table: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // tableCell の ID で UITableViewCell のインスタンスを生成
        let cell = tableView.dequeueReusableCell(withIdentifier: "WordCell", for: indexPath) as! WordCell


        return cell
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

xibファイルの呼び出し

Sample
let nibDefault: UINib = UINib(nibName: "ListTableViewCell", bundle: nil)
listTableView.register(nibDefault, forCellReuseIdentifier: "ListTableViewCell")

UserDefaultsで値の端末保存

Sample
// UserDefaults のインスタンス
let userDefaults = UserDefaults.standard

// Keyを指定して保存
userDefaults.set(str, forKey: "KEY")
userDefaults.synchronize()

// Keyを指定して読み込み
let str: String = userDefaults.object(forKey: "KEY") as! String

// Key の値を削除
userDefaults.removeObject(forKey: "KEY")

UIViewをアニメーション

Sample
UIView.animate(withDuration: 1.0, animations: {
    aView.alpha = 0
}, completion: { finished in
    aView.removeFromSuperview()
})

クロージャーを使ったシングルトン

Smaple
class Manager {
    // 変数、定数の宣言

    static var sharedManager: Manager = {
        return Manager()
    }()
    private init() {
    }
}

ButtonのカスタマイズやUIView装飾

Sample
//UIViewの装飾
btn.layer.borderColor = UIColor.brown.cgColor        
btn.layer.borderWidth = 1.0
btn.layer.cornerRadius = 5.0
btn.layer.masksToBounds = true

//ボタン専用
btn.setTitle("押されました", for: UIControlState.normal)

アラートビュー

Sample
 let alert = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .alert)

 alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        print("OKが押された") // 処理
    }))
 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

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

TextFieldのキーボードの上げ下げ

Sample

class ViewController: UIViewController ,UITextFieldDelegate{
    @IBOutlet var sampleTextField: UITextField!
    var initPoint : CGPoint!


    override func viewDidLoad() {
        super.viewDidLoad()
        initPoint = self.view.center
        sampleTextField.delegate = self
    }

    // テキストフィールドがフォーカスされた時の処理
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if ( textField.center.y > self.view.center.y){
            UIView.animate(withDuration: 0.4, animations: {
                let moveY = textField.center.y - self.view.center.y
                self.view.frame = self.view.bounds.offsetBy(dx: 0, dy: -moveY)
            })
        }
        return true
    }

    // テキストフィールドでの編集が終わろうとするときの処理
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        UIView.animate(withDuration: 0.2, animations: {
            self.view.center = self.initPoint
        })
        return true
    }

    // 改行ボタンを押した時の処理
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        // キーボードを隠す
        textField.resignFirstResponder()
        return true
    }
}

画面遷移

Sample
//storyBoard上のsegueを使用

//Present Modally で遷移した後の戻る
self.dismiss(animated: true, completion: nil)

//navigationcontrollerを使用

最後に

間違えやまた頻繁に使いそうなTipsがあれば随時更新(修正、追記、削除)します。
コメントに書いて頂ければ、更新します:relaxed:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0