0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

iOS14 DatePickerの表示部分をカスタマイズしたい

Posted at

前提

提供部品(UIKit)のプロパティで変更することは厳しかったため
DatePickerにラベルを重ねることによって実装しています。

実装

カスタムクラス作成

CustomDatePicker
import UIKit

class CustomDatePicker: UIDatePicker {
    let label = UILabel()
    // こちらはフォーマットのデフォルトです
    // 変更予定のため任意で構わないです
    private var format = "MMM d yyyy hh:mm"
    
    private func updateLabel() {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "ja_JP")
        formatter.setLocalizedDateFormatFromTemplate(self.format)
        label.text = formatter.string(from: date)
    }
    
    // このメソッドより↑のデフォルトを書き換えます
    func setLabelFormat(format: String) {
        self.format = format
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        addSubview(label)
    }
    
    // カスタマイズに苦戦したものとはお別れ
    func makeTransparent(view: UIView) {
        view.subviews.forEach({ $0.subviews.forEach({ $0.removeFromSuperview() }) })
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        makeTransparent(view: self)
        label.frame = CGRect(origin: .zero, size: frame.size)
        updateLabel()
    }
}

使用方法

storyboard, xib使用

DatePickerを配置
スクリーンショット 2021-04-06 15.04.52.png

Classにさきほど作成したものを適応
スクリーンショット 2021-04-06 15.05.08.png

ViewControllerに紐付けて

ViewController
@IBOutlet weak var timeDatePicker: CustomDatePicker!

func configDatePicker() {
    // format指定
    self.timeDatePicker.setLabelFormat(format: "Hm")
    // DataPicker自体のカスタマイズ
    self.timeDatePicker.datePickerMode = .time
    // 表示部分のカスタマイズ
    self.timeDatePicker.label.textAlignment = .center
    self.timeDatePicker.label.backgroundColor = .darkGray
}

結果

動画の撮り方わからないため画像ですみません。

Label Picker
スクリーンショット 2021-04-06 15.12.02.png スクリーンショット 2021-04-06 15.12.11.png

最後に

Pickerの使用するModeによってフォーマットを変更する必要がありますが、
プロジェクト単位で仕様が決まっていればそこもカスタムViewに組み込む形でいいかと思います。

またコードにてレイアウトを使用している方も同様に利用できます。(当たり前ですが、、w)

簡易的な記事なため、「もっとここ詳しく」などのコメントもお待ちしております。

pickerの仕様が変わりTextFieldにaddするような形じゃないため、
以前のものよりレイアウトに制限があるとおもい使用をさけてましたが、
ios14以上のみをターゲットにするアプリを作成する予定が入ったため
ドラムはなーーーと思い作成しました。

同じような問題をかかえて使用をやめた方などの参考に少しでもなればなと思います。

短いですが以上です。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?