FromNowOn2017 / SWIFT

SWIFTのサンプルの投稿
0 stars 0 forks source link

EditView #4

Open FromNowOn2017 opened 6 years ago

FromNowOn2017 commented 6 years ago

import UIKit //画面のもデリデートさせる class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var txtTitle: UITextField! @IBOutlet weak var txtDate: UITextField!

// BaseViewを隠すためのボタンです。 //normalのボタンを作成(typeはボタンのタイプです。) let closeBtn:UIButton = UIButton(type: .system) // DatePickerが乗るView(最初に隠しておく) let baseView:UIView = UIView(frame: CGRect(x:0,y:720,width:200,height:250)) //baseViewを隠す func closeBaseView(){ UIView.animate(withDuration: 0.5, animations: {() -> Void in self.baseView.frame.origin = CGPoint(x: 0,y: self.view.frame.size.height) }) }

///DatePickerで日付を選択した時、日付のTextFieldに値を表示
func showDateSelected(sender:UIDatePicker){
    ///フォーマットを設定(文字列に変換するための)
    let df = DateFormatter()
    df.dateFormat = "yyyy / MM / dd"
    ///日付型から文字列に変換
    let strSelectedDate = df.string(from: sender.date)
    ///TextFieldに変換した文字列を表示
    txtDate.text = strSelectedDate

}

///BaseViewに載せるDatePicker
let myDatePicker: UIDatePicker = UIDatePicker(frame: CGRect(x: 10, y: 25, width: 300, height: 200))

// キーボードを閉じる @IBAction func tapReturn1( sender: UITextField) { } // キーボードを閉じる @IBAction func tapReturn2( sender: UITextField) { } // テキストフィールド入力開始時に起動 func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{ print("tag:(textField.tag)") switch textField.tag { case 1://キーボードが表示される return true case 2://キーボードが表示されない // 日付を入力するテキストフィールド //baseViewの表示(下に隠しているところから見える) UIView.animate(withDuration: 0.5, animations: {() -> Void in self.baseView.frame.origin = CGPoint(x: 0,y: self.view.frame.size.height - self.baseView.frame.height) }) return false default://キーボードが表示される return true } }

override func viewDidLoad() {
    super.viewDidLoad()

    ///DatePickerのモードを日付に設定
    myDatePicker.datePickerMode = UIDatePickerMode.date

    ///DatePickerの選択された日付が変更された時発動するイベントを追加
    myDatePicker.addTarget(self, action: #selector(showDateSelected(sender:)), for: .valueChanged)

/// DatePickerをbaseViewに追加 baseView.addSubview(myDatePicker)

// baseViewを下にViewの下ぴったり配置、横幅ぴったりの大きさにしておく //self.view.frame.size.height左端にぴったり設定 baseView.frame.origin = CGPoint(x: 0, y: self.view.frame.size.height) baseView.frame.size = CGSize(width: self.view.frame.size.width,height:baseView.frame.height) // baseViewに背景色をつける baseView.backgroundColor = UIColor.gray // 元の画面に追加 self.view.addSubview(baseView) //closeBtnの大きさ、位置を設定 closeBtn.frame = CGRect(x: self.view.frame.width - 60, y: 0, width: 50, height: 20) //タイトルを設定 closeBtn.setTitle("Close", for: .normal) //イベントの作成 ボタンがおされたらcloseBaseViewを実行する closeBtn.addTarget(self, action: #selector(closeBaseView),for: .touchUpInside) //baseviewにCloseBtnを配置 baseView.addSubview(closeBtn) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }