如何在swift(iOS)中创建单选按钮和复选框?

Van*_*ian 71 checkbox xcode radio-button ios swift

我正在开发一个允许进行调查的应用程序.我的布局是基于XML的问题生成的.

我需要创建单选按钮(单选)和复选框(多个答案).我找不到任何对swift有用的东西.

有没有人有想法?

cru*_*bio 135

复选框

你可以创建自己的CheckBox控件,使用Swift扩展UIButton:

import UIKit

class CheckBox: UIButton {
    // Images
    let checkedImage = UIImage(named: "ic_check_box")! as UIImage
    let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage

    // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, for: UIControl.State.normal)
            } else {
                self.setImage(uncheckedImage, for: UIControlState.normal)
            }
        }
    }

    override func awakeFromNib() {
        self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
        self.isChecked = false
    }

    @objc func buttonClicked(sender: UIButton) {
        if sender == self {
            isChecked = !isChecked
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用Interface Builder将其添加到您的视图中:

在此输入图像描述

单选按钮

无线电按钮可以以类似的方式解决.

例如,经典的性别选择女人 - 男人:

在此输入图像描述

import UIKit

class RadioButton: UIButton {
    var alternateButton:Array<RadioButton>?

    override func awakeFromNib() {
        self.layer.cornerRadius = 5
        self.layer.borderWidth = 2.0
        self.layer.masksToBounds = true
    }

    func unselectAlternateButtons(){
        if alternateButton != nil {
            self.isSelected = true

            for aButton:RadioButton in alternateButton! {
                aButton.isSelected = false
            }
        }else{
            toggleButton()
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        unselectAlternateButtons()
        super.touchesBegan(touches, with: event)
    }

    func toggleButton(){
        self.isSelected = !isSelected
    }

    override var isSelected: Bool {
        didSet {
            if isSelected {
                self.layer.borderColor = Color.turquoise.cgColor
            } else {
                self.layer.borderColor = Color.grey_99.cgColor
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样初始化你的单选按钮:

    override func awakeFromNib() {
        self.view.layoutIfNeeded()

        womanRadioButton.selected = true
        manRadioButton.selected = false
    }

    override func viewDidLoad() {
        womanRadioButton?.alternateButton = [manRadioButton!]
        manRadioButton?.alternateButton = [womanRadioButton!]
    }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

  • @Nitesh,您好,您可以使用公共bool属性isChecked获得Checked状态,例如:if myCheckbox.isChecked {...} (2认同)

Rei*_*ica 36

对于Radio Buttons和CheckBoxes,没有任何内置功能.

您可以自己轻松实现Checkbox.您可以为UIControlStateNormal的按钮设置uncheckedImage,为UIControlStateSelected设置checkedImage.现在点按此按钮将更改其图像,并在已选中和未选中图像之间切换.

要使用单选按钮,您必须保留Array所有要用作单选按钮的按钮.无论何时按下按钮,您都需要取消选中阵列中的所有其他按钮.

对于单选按钮,您可以使用SSRadioButtonsController 您可以创建一个控制器对象并向其添加按钮数组

var radioButtonController = SSRadioButtonsController()
radioButtonController.setButtonsArray([button1!,button2!,button3!])
Run Code Online (Sandbox Code Playgroud)

其主要原理是像这样在这里.


Dav*_*Liu 21

查看DLRadioButton.您可以直接从Interface Builder添加和自定义单选按钮.也Swift完美地工作.

适用于iOS的Swift单选按钮

更新:版本1.3.2添加了方形按钮,也提高了性能.

更新:版本1.4.4添加了多个选择选项,也可以用作复选框.

更新:版本1.4.7添加了RTL语言支持.


Ras*_*tif 20

Swift 5,带动画的复选框

注: -如果你要删除的blue同时,背景isSelected的变化从UIButton的类型SystemCustom

创建按钮的出口

@IBOutlet weak var checkBoxOutlet:UIButton!{
        didSet{
            checkBoxOutlet.setImage(UIImage(named:"unchecked"), for: .normal)
            checkBoxOutlet.setImage(UIImage(named:"checked"), for: .selected)
        }
    }
Run Code Online (Sandbox Code Playgroud)

创建 UIButton 的扩展

extension UIButton {
    //MARK:- Animate check mark
    func checkboxAnimation(closure: @escaping () -> Void){
        guard let image = self.imageView else {return}
        
        UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveLinear, animations: {
            image.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
            
        }) { (success) in
            UIView.animate(withDuration: 0.1, delay: 0, options: .curveLinear, animations: {
                self.isSelected = !self.isSelected
                //to-do
                closure()
                image.transform = .identity
            }, completion: nil)
        }
        
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用

 @IBAction func checkbox(_ sender: UIButton){
        sender.checkboxAnimation {
            print("I'm done")
            //here you can also track the Checked, UnChecked state with sender.isSelected
            print(sender.isSelected)
            
        }
}
Run Code Online (Sandbox Code Playgroud)

检查我的复选框和单选按钮示例 https://github.com/rashidlatif55/CheckBoxAndRadioButton

  • 我认为这值得更多选票。感谢您提供优雅的解决方案。 (2认同)

小智 8

你可以使用一个非常棒的库(你可以用它代替UISwitch):https://github.com/Boris-Em/BEMCheckBox

设置很简单:

BEMCheckBox *myCheckBox = [[BEMCheckBox alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[self.view addSubview:myCheckBox];
Run Code Online (Sandbox Code Playgroud)

它提供圆形和方形类型复选框

在此输入图像描述

它也做动画:

在此输入图像描述


Gul*_*ulz 6

更短的 ios swift 4 版本:

@IBAction func checkBoxBtnTapped(_ sender: UIButton) {
        if checkBoxBtn.isSelected {
            checkBoxBtn.setBackgroundImage(#imageLiteral(resourceName: "ic_signup_unchecked"), for: .normal)
        } else {
            checkBoxBtn.setBackgroundImage(#imageLiteral(resourceName: "ic_signup_checked"), for:.normal)
        }
        checkBoxBtn.isSelected = !checkBoxBtn.isSelected
    }
Run Code Online (Sandbox Code Playgroud)


Akh*_*ngh 6

Swift 4.2中单选按钮不使用第三方库的解决方案

创建 RadioButtonController.swift 文件并将以下代码放入其中:

import UIKit

class RadioButtonController: NSObject {
    var buttonsArray: [UIButton]! {
        didSet {
            for b in buttonsArray {
                b.setImage(UIImage(named: "radio_off"), for: .normal)
                b.setImage(UIImage(named: "radio_on"), for: .selected)
            }
        }
    }
    var selectedButton: UIButton?
    var defaultButton: UIButton = UIButton() {
        didSet {
            buttonArrayUpdated(buttonSelected: self.defaultButton)
        }
    }

    func buttonArrayUpdated(buttonSelected: UIButton) {
        for b in buttonsArray {
            if b == buttonSelected {
                selectedButton = b
                b.isSelected = true
            } else {
                b.isSelected = false
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的视图控制器文件中如下使用它:

import UIKit

class CheckoutVC: UIViewController {

    @IBOutlet weak var btnPaytm: UIButton!
    @IBOutlet weak var btnOnline: UIButton!
    @IBOutlet weak var btnCOD: UIButton!

    let radioController: RadioButtonController = RadioButtonController()

    override func viewDidLoad() {
        super.viewDidLoad()

        radioController.buttonsArray = [btnPaytm,btnCOD,btnOnline]
        radioController.defaultButton = btnPaytm
    }

    @IBAction func btnPaytmAction(_ sender: UIButton) {
        radioController.buttonArrayUpdated(buttonSelected: sender)
    }

    @IBAction func btnOnlineAction(_ sender: UIButton) {
        radioController.buttonArrayUpdated(buttonSelected: sender)
    }

    @IBAction func btnCodAction(_ sender: UIButton) {
        radioController.buttonArrayUpdated(buttonSelected: sender)
    }
}
Run Code Online (Sandbox Code Playgroud)

请务必在 Assets 中添加 radio_off 和 radio_on 图像。

图像上的收音机 无线电关闭图像

结果:

单选按钮结果

  • 整洁且可重复使用的解决方案。谢谢! (2认同)

Pra*_*ani 5

一个非常简单的复选框控件。

 @IBAction func btn_box(sender: UIButton) {
    if (btn_box.selected == true)
    {
        btn_box.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal)

            btn_box.selected = false;
    }
    else
    {
        btn_box.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal)

        btn_box.selected = true;
    }
}
Run Code Online (Sandbox Code Playgroud)