【Swift】UserNotification(ローカル通知)の使い方
完成図
↓destination == "Ken"の時
解説
※注意点
・今回はバックグラウンドでの実装
・”送信する”を押して、すぐにアプリを閉じないと、ローカル通知が発動しない
・発動すれば、画面上部 & 通知センターに表示される
ストーリーボード
ソースコード
import UIKit import UserNotifications class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var honbunTextField: UITextView! //送り先を受け取る var destination = "" //本文を受け取る var message = "" //identifier用の変数 let NotificationIdentifier = "ID" override func viewDidLoad() { super.viewDidLoad() //デリゲートを取得 nameTextField.delegate = self } @IBAction func send(_ sender: Any) { //送り先を代入する destination = nameTextField.text! //本文を代入する message = honbunTextField.text! //メッセージを送信する gopush() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //ローカル通知の許可等 func gopush() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in //もし通知が許可されているなら if settings.authorizationStatus == .authorized { //通知 self.push() //もし通知が許可されてないなら } else { UNUserNotificationCenter.current().requestAuthorization( options: [.sound,.badge,.alert],completionHandler: { (granted, error) in if let error = error { print(error) } else { if (granted) { self.push() } } }) } } } //ローカル通知内での処理 func push() { //指定した文章と同じかどうか if message == "" { //UserNotificationのインスタンス let content = UNMutableNotificationContent() //送り主で条件分岐 switch destination { case "Amy": //メッセージのタイトル content.title = "All right!!" //メッセージの本文 content.body = "I will put on my favorite clothes!" //通知に貼り付ける画像のURL if let url = Bundle.main.url(forResource: "Amy", withExtension: "png"),let attach = try? UNNotificationAttachment(identifier: NotificationIdentifier, url: url, options: nil) { content.attachments.append(attach) } case "Karen": content.title = "OK!" content.body = "I'm looking forward to watching a movie with everyone!" if let url = Bundle.main.url(forResource: "Karen", withExtension: "png"), let attach = try? UNNotificationAttachment(identifier: NotificationIdentifier, url: url, options: nil) { content.attachments.append(attach) } case "Ken": content.title = "Oh Yes!" content.body = "Let's release the stress accumulated in the exam tomorrow at once!" if let url = Bundle.main.url(forResource: "Ken", withExtension: "png"), let attach = try? UNNotificationAttachment(identifier: NotificationIdentifier, url: url, options: nil) { content.attachments.append(attach) } case "Mike": content.title = "I want to go early" content.body = "Finally I can get out of boring lessons and I can not wait for tomorrow's event" if let url = Bundle.main.url(forResource: "Mike", withExtension: "png"), let attach = try? UNNotificationAttachment(identifier: NotificationIdentifier, url: url, options: nil) { content.attachments.append(attach) } default: content.title = "It is a mistake email." content.body = "Who are you? It is fine if sales" } //5秒後に通知 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3.0, repeats: false) //トリガーと内容を内包 let notificationrequest = UNNotificationRequest(identifier: NotificationIdentifier, content: content, trigger: trigger) //エラー処理 UNUserNotificationCenter.current().add(notificationrequest) { (error) in if let error = error { print(error) } else { print("通知されました") } } } else { print("もう一度やり直してください。") } } }
【Swift】CollectionViewのページめくりアニメーション
完成図
↓1度目のスワイプ ↓2度目のスワイプ
解説
※注意点
・ページめくりを実装するには、
- Scroll DirectionをHorizontalに指定
- Scrolling - Horizontal Indicatorにチェック
- MidSpacingの値を0に指定
する必要がある。
↓
・今回はカスタムセルを使ってるが、何もいじってないので、使わなくてもOKかも。
・CollectionViewのsizeItemForAtをview.frame.width/heightにする
・ViewControllerを生成し、ConllecionViewで実装する
ストーリーボード
ソースコード
import UIKit class ViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self } @IBOutlet weak var collectionView: UICollectionView! { //カスタムセルをcollectionViewに登録 didSet { collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell") } } //ページに表示する色 let dataSource: [UIColor] = [.red, .green, .blue, .cyan, .yellow, .magenta] // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cv = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) //ViewControllerを生成 let viewController = UIViewController() //ViewControllerの位置とサイズを設定 viewController.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) //ViewControllerの背景色を設定 viewController.view.backgroundColor = dataSource[indexPath.row] //collectionViewにViewControllerをセット cv.addSubview(viewController.view) return cv } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: view.frame.height) } }
【Swift】PickerView&DatePickerの使い方
完成図
↓”現在時刻”を押した場合 ↓”10分後へ”を押した場合
解説
「DatePicker」
・日時を扱うなら絶対にこれ
・NSDate()や正確な日時を指定するのに必要な処理を省略できる
・現在時刻をdatePicker.date = Date()だけで取得できる手軽さ
・??分後に移動する場合は、datePicker.date=Date(60(秒)*??(分))、だけでOK
「PickerView」
・構造はセルと同じ
・numberOfConponents, numberOfRowsInConponent, titleForRowは、セルが用意するnumberOfSection, numberRowInSection, cellForAt、と似ている
・異なる処理や値を設定したPickerViewの配置は困難。
・1つのPickerViewで値や処理を変えればいい
ストーリーボード
ソースコード
import UIKit class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource { @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var textPicker: UIPickerView! let text:[String] = ["1","2","3","4","5","6"] override func viewDidLoad() { super.viewDidLoad() textPicker.delegate = self textPicker.dataSource = self // Do any additional setup after loading the view, typically from a nib. } //DatePickerのメソッド @IBAction func nowDate(_ sender: Any) { datePicker.date = Date() } @IBAction func laterDate(_ sender: Any) { datePicker.date = Date(timeInterval: 60*10, since: datePicker.date) } @IBAction func beforeDate(_ sender: Any) { datePicker.date = Date(timeInterval: -60*10, since: datePicker.date) } //PickerViewのメソッド func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return text.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return text[row] } }
【プログラミング】キーボードの入力位置を変えずにdeleteする
普通にdeleteキーを押せば、
↓
左に入力位置が移動し、左の文字を消していく。
しかし、
入力位置を移動せず
右の文字を消していく
が可能だとしたら?
方法は、delete + fn、キーの同時押し。
↓
右側の文字を消すのにわざわざ→キーを連打する人はおさらばできるだろう。