LoginSignup
4
6

More than 3 years have passed since last update.

iOS(Swift)でラジオボタン[YSRadioButton]

Last updated at Posted at 2019-09-05

iOSアプリを開発していてブラウザ標準のようなラジオボタンを使いたいと思ったことはありませんか?そんな時のためにシンプルなデザインのswift製ラジオボタンライブラリを作成しました。各種プロパティを設定することでデザインもある程度自由に変更することができます。

Sep-05-2019 10-48-11.gifradioButton3.gifradioButton2.gif

GitHubはこちら

CocoaPodsでインストールできるのでとても簡単です。それでは早速インストールの手順を説明します。

CocoaPods

Podfileに

Podfile
use_frameworks!

pod 'YSRadioButton', :git => 'https://github.com/sekies/YSRadioButton.git'

と追加します。

pod install します。

Usage

YSRadioButtonをインポートします。

ViewController.swift
 import YSRadioButton

任意のUIViewContorollerでYSRadioButtonViewControllerDelegate プロトコルに準拠します。

ViewController.swift
 class ViewController: UIViewController,YSRadioButtonViewControllerDelegate {

YSRadioButtonViewControllerインスタンスを生成します。生成時にラジオボタンのラベルを配列で指定します。

ViewController.swift
  let radio = YSRadioButtonViewController(labels: ["Orange","GrapeFruits","Banana"])

delegateと各種デザインプロパティを設定します。必須となるのはdelegateのみです。

ViewController.swift
  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に依存します。

ViewController.swift
  addChild(radio)
  radio.view.frame = container.bounds
  container.addSubview(radio.view)
  radio.didMove(toParent: self)

デリゲートメソッドを実装します。ラジオボタンを選択するとこのメソッドが呼ばれます。YSRadioButtonViewController生成時に追加した配列の順にIntが割り振られます。

ViewController.swift
  func didYSRadioButtonSelect(no: Int) {
    print(no)
  }

コードの全体像です。

ViewController.swift
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)
    }

}

4
6
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
4
6