iOSアプリを開発していてブラウザ標準のようなラジオボタンを使いたいと思ったことはありませんか?そんな時のためにシンプルなデザインのswift製ラジオボタンライブラリを作成しました。各種プロパティを設定することでデザインもある程度自由に変更することができます。
CocoaPodsでインストールできるのでとても簡単です。それでは早速インストールの手順を説明します。
CocoaPods
Podfileに
use_frameworks!
pod 'YSRadioButton', :git => 'https://github.com/sekies/YSRadioButton.git'
と追加します。
pod install します。
Usage
YSRadioButtonをインポートします。
import YSRadioButton
任意のUIViewContorollerでYSRadioButtonViewControllerDelegate
プロトコルに準拠します。
class ViewController: UIViewController,YSRadioButtonViewControllerDelegate {
YSRadioButtonViewController
インスタンスを生成します。生成時にラジオボタンのラベルを配列で指定します。
let radio = YSRadioButtonViewController(labels: ["Orange","GrapeFruits","Banana"])
delegateと各種デザインプロパティを設定します。必須となるのはdelegateのみです。
radio.delegate = self
radio.font = UIFont.systemFont(ofSize: 18)
radio.labelColor = .black
radio.labelMargin = 0
radio.lineWidth = 1
radio.radioHeadFillSize = 0.6
radio.radioHeadMargin = 5
radio.radioHeadStroke = .darkGray
radio.radioHeadFill = .red
親UIViewControllerに生成したYSRadioButtonViewControllerをaddChildしコンテナとなるUIViewにYSRadioButtonViewControllerのviewをaddSubviewします。ラジオボタンの位置はコンテナとなるUIViewに依存します。
addChild(radio)
radio.view.frame = container.bounds
container.addSubview(radio.view)
radio.didMove(toParent: self)
デリゲートメソッドを実装します。ラジオボタンを選択するとこのメソッドが呼ばれます。YSRadioButtonViewController生成時に追加した配列の順にIntが割り振られます。
func didYSRadioButtonSelect(no: Int) {
print(no)
}
コードの全体像です。
import UIKit
import YSRadioButton
class ViewController: UIViewController, YSRadioButtonViewControllerDelegate {
@IBOutlet weak var container: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let radio = YSRadioButtonViewController(labels: ["Orange","GrapeFruits","Banana"])
radio.delegate = self
radio.font = UIFont.systemFont(ofSize: 18)
radio.labelColor = .black
radio.labelMargin = 0
radio.lineWidth = 1
radio.radioHeadFillSize = 0.6
radio.radioHeadMargin = 5
radio.radioHeadStroke = .darkGray
radio.radioHeadFill = .red
addChild(radio)
radio.view.frame = container.bounds
container.addSubview(radio.view)
radio.didMove(toParent: self)
}
func didYSRadioButtonSelect(no: Int) {
print(no)
}
}