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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29117759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:14:57  来源:igfitidea点击:

How to create radio buttons and checkbox in swift (iOS)?

iosxcodeswiftcheckboxradio-button

提问by Vannian

I am developing an app that allows to do survey. My layout is generated from XML based questions.

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

I need to create radio buttons (single choice) and checkboxes (multiple answers). I did not find anything useful for swift.

我需要创建单选按钮(单选)和复选框(多选)。我没有发现任何对 swift 有用的东西。

Does anyone have an idea?

有没有人有想法?

采纳答案by Shamas S - Reinstate Monica

For Radio Buttons and CheckBoxes there is nothing that comes built in.

对于单选按钮和复选框,没有内置任何内容。

You can implement Checkboxes easily yourself. You can set an uncheckedImage for your button for UIControlStateNormal and a checkedImage for your UIControlStateSelected. Now on tap, the button will change its image and alternate between checked and unchecked image.

您可以自己轻松实现复选框。您可以为 UIControlStateNormal 的按钮设置一个 uncheckedImage,为 UIControlStateSelected 设置一个 checkedImage。现在点击,按钮将更改其图像并在选中和未选中的图像之间交替。

To use radio buttons, you have to keep an Arrayfor all the buttons that you want to behave as radio buttons. Whenever a button is pressed, you need to uncheck all other buttons in the array.

要使用单选按钮,您必须Array为所有要用作单选按钮的按钮保留一个。每当按下按钮时,您需要取消选中阵列中的所有其他按钮。

For radio buttons you can use SSRadioButtonsControllerYou can create a controller object and add buttons array to it like

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

var radioButtonController = SSRadioButtonsController()
radioButtonController.setButtonsArray([button1!,button2!,button3!])

The main principle is something like this here.

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

回答by crubio

Checkbox

复选框

You can create your own CheckBox control extending UIButton with Swift:

您可以创建自己的 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: UIControl.State.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
        }
    }
}

And then add it to your views with Interface Builder:

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

enter image description here

在此处输入图片说明

Radio Buttons

单选按钮

Radio Buttons can be solved in a similar way.

单选按钮可以用类似的方式解决。

For example, the classic gender selection Woman- Man:

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

enter image description here

在此处输入图片说明

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
            }
        }
    }
}

You can init your radio buttons like this:

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

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

        womanRadioButton.selected = true
        manRadioButton.selected = false
    }

    override func viewDidLoad() {
        womanRadioButton?.alternateButton = [manRadioButton!]
        manRadioButton?.alternateButton = [womanRadioButton!]
    }

Hope it helps.

希望能帮助到你。

回答by David Liu

Check out DLRadioButton. You can add and customize radio buttons directly from the Interface Builder. Also works with Swiftperfectly.

查看DLRadioButton。您可以直接从 Interface Builder 添加和自定义单选按钮。也可以Swift完美配合。

Swift Radio Button for iOS

适用于 iOS 的 Swift 单选按钮

Update: version 1.3.2added square buttons, also improved performance.

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

Update: version 1.4.4added multiple selection option, can be used as checkbox as well.

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

Update: version 1.4.7added RTL language support.

更新:版本1.4.7增加了 RTL 语言支持。

回答by Calvin Alvin

There's a really great library out there you can use for this (you can actually use this in place of UISwitch): https://github.com/Boris-Em/BEMCheckBox

有一个非常棒的库可供您使用(您实际上可以使用它代替UISwitch):https: //github.com/Boris-Em/BEMCheckBox

Setup is easy:

设置很简单:

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

It provides for circle and square type checkboxes

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

enter image description here

在此处输入图片说明

And it also does animations:

它也做动画:

enter image description here

在此处输入图片说明

回答by Gulz

shorter ios swift 4 version:

更短的 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
    }

回答by Pragnesh Vitthani

A very simple checkbox control.

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

 @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;
    }
}

回答by Rashid Latif

Swift 5, Checkbox with animation

Swift 5,带动画的复选框

Create an outlet of the button

创建按钮的出口

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

Create an extension of UIButton

创建 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)
        }

    }
}

How to use

如何使用

 @IBAction func checkbox(_ sender: UIButton){
        sender.checkboxAnimation {
            print("I'm done")
        }
}

回答by Krutarth Patel

Steps to Create Radio Button

创建单选按钮的步骤

BasicStep : take Two Button. set image for both like selected and unselected. than add action to both button. now start code

BasicStep :取两个按钮。为选中和未选中的图像设置图像。比向两个按钮添加动作。现在开始代码

1)Create variable :

1)创建变量:

var btnTag    : Int = 0

2)In ViewDidLoad Define :

2)在 ViewDidLoad 中定义:

 btnTag = btnSelected.tag

3)Now In Selected Tap Action :

3)现在在选定的点击操作中:

 @IBAction func btnSelectedTapped(sender: AnyObject) {
    btnTag = 1
    if btnTag == 1 {
      btnSelected.setImage(UIImage(named: "icon_radioSelected"), forState: .Normal)
      btnUnSelected.setImage(UIImage(named: "icon_radioUnSelected"), forState: .Normal)
     btnTag = 0
    }
}

4)Do code for UnCheck Button

4)为UnCheck Button做代码

 @IBAction func btnUnSelectedTapped(sender: AnyObject) {
    btnTag = 1
    if btnTag == 1 {
        btnUnSelected.setImage(UIImage(named: "icon_radioSelected"), forState: .Normal)
        btnSelected.setImage(UIImage(named: "icon_radioUnSelected"), forState: .Normal)
        btnTag = 0
    }
}

Radio Button is Ready for you

单选按钮已为您准备就绪

回答by Salil Dhawan

For a checkbox, you don't need to subclass the UIButton. It already has the isSelectedproperty to handle this.

对于复选框,您不需要子类化 UIButton。它已经拥有isSelected处理这个问题的能力。

checkbox = UIButton.init(type: .custom)
checkbox.setImage(UIImage.init(named: "iconCheckboxOutlined"), for: .normal)
checkbox.setImage(UIImage.init(named: "iconCheckboxFilled"), for: .selected)
checkbox.addTarget(self, action: #selector(self.toggleCheckboxSelection), for: .touchUpInside)

Then in the action method toggle it's isSelectedstate.

然后在动作方法中切换它的isSelected状态。

@objc func toggleCheckboxSelection() {
    checkbox.isSelected = !checkbox.isSelected
}

回答by got2jam

I made a super simple class to handle this in a Mac application I'm working on. Hopefully, this is helpful to someone

我制作了一个超级简单的类来在我正在开发的 Mac 应用程序中处理这个问题。希望这对某人有帮助

RadioButtonController Class:

RadioButtonController 类:

class RadioButtonController: NSObject {

var buttonArray : [NSButton] = []
var currentleySelectedButton : NSButton?
var defaultButton : NSButton = NSButton() {
    didSet {
        buttonArrayUpdated(buttonSelected: self.defaultButton)
    }
}

func buttonArrayUpdated(buttonSelected : NSButton) {
    for button in buttonArray {
        if button == buttonSelected {
            currentleySelectedButton = button
            button.state = .on
        } else {
            button.state = .off
        }
    }
}

}

}

Implementation in View Controller:

在视图控制器中的实现:

class OnboardingDefaultLaunchConfiguration: NSViewController {

let radioButtonController : RadioButtonController = RadioButtonController()
@IBOutlet weak var firstRadioButton: NSButton!
@IBOutlet weak var secondRadioButton: NSButton!

@IBAction func folderRadioButtonSelected(_ sender: Any) {
    radioButtonController.buttonArrayUpdated(buttonSelected: folderGroupRadioButton)
}

@IBAction func fileListRadioButtonSelected(_ sender: Any) {
    radioButtonController.buttonArrayUpdated(buttonSelected: fileListRadioButton)
}

override func viewDidLoad() {
    super.viewDidLoad()
    radioButtonController.buttonArray = [firstRadioButton, secondRadioButton]
    radioButtonController.defaultButton = firstRadioButton
}

}