LoginSignup
2
0

More than 5 years have passed since last update.

UIButtonでソートするのめんどくさくない?

Last updated at Posted at 2017-11-30

UIButtonでUITableViewのソートとかを管理する時に、昇順・降順だけならnormalとselectedで管理できるんですが、複数ソートボタンがあった際に、昇順・降順・ソート無しを管理しようとすると割りと面倒だったりします。

そんなわけでライブラリ作りました🦎

PKPK-Carnage/OTSortButton

こんな感じ

otsortbuttondemo

機能

・ソート無し・昇順・降順を管理可能
・それぞれに背景色・文字色・ソート画像色(昇順・降順のみ)・背景画像を設定可能

導入

CocoaPods・Carthageで導入、もしくはライブラリのClassフォルダのソースを直接プロジェクトに追加してください。

CocoaPods

pod 'OTSortButton'

Carthage

github "PKPK-Carnage/OTSortButton"

使い方

ソートボタンにしたいボタンのカスタムクラスにOTSortButtonを設定します。
2017-09-15 21 10 54

IBInspectableで設定表示の設定が可能です。

2017-09-15 21 27 45

インポートして、IBOutletCollectionでOTSortButtonをまとめます。

import
import OTSortButton

@IBOutlet var sortButtonCollection: [OTSortButton]!

必要であれば、ボタンに値を保持しておけるので、Dictionaryのキーなどを入れるといいと思います。

sortkey
@IBOutlet weak var yourSortButton: OTSortButton!

yourSortButton.sortKey = "yourKey"

IBActionを設定します。

IBAction
@IBAction func tappedSortButton(_ sender: OTSortButton) {
    for sortButton in sortButtonCollection {
        if sortButton == sender {
            let key = sortButton.sortKey
            switch sortButton.sortType {
                case .none:

                    sortButton.sortType = .ascend
                    //ここで昇順のソートをする
                    //e.g. sortedArray = yourArray.sorted(by: { $0[key]! < $1[key]! })

                case .ascend:

                    sortButton.sortType = .descend
                    // ここで降順のソートをする。
                    //e.g. sortedArray = yourArray.sorted(by: { $0[key]! > $1[key]! })

                case .descend:

                    sortButton.sortType = .none
                    // ここでソート無しにする。
                    //e.g. sortedArray = yourArray     
            }
        } else {
            sortButton.sortType = .none
        }
    }
    tableView.reloadData()
}

まとめ

これでもめんどくさいね。

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