Ios Swift中的动态单选按钮?

Ios Swift中的动态单选按钮?,ios,swift,xcode,Ios,Swift,Xcode,我试图找到一种在swift中实现单选按钮的简单方法,但没有成功。是否有易于使用的实现 提前感谢我在网上没有找到任何合适的答案,所以我正在分享我的代码,以便在swift中创建动态自定义单选按钮。 我希望这能对某些人有所帮助 这个区块显示了动态部分,但是我完全鼓励您从提供的链接下载完整的项目,以便您能够理解整个逻辑 import UIKit import DLRadioButton //Delegate to manage the Polls protocol QuestionsDialogDel

我试图找到一种在swift中实现单选按钮的简单方法,但没有成功。是否有易于使用的实现


提前感谢

我在网上没有找到任何合适的答案,所以我正在分享我的代码,以便在swift中创建动态自定义单选按钮。 我希望这能对某些人有所帮助

这个区块显示了动态部分,但是我完全鼓励您从提供的链接下载完整的项目,以便您能够理解整个逻辑

import UIKit
import DLRadioButton

//Delegate to manage the Polls
protocol QuestionsDialogDelegate : class{
    func questionsAnswered(polls: [Poll])
}

class QuestionsDialog: UIViewController {

    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var nestedView: UIView!
    weak var delegate: QuestionsDialogDelegate?
    var questions : [Question]!
    var polls = [Poll]()
    var serviceType : Int = 0
    var indexView : Int = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        //setting the stack view properties
        stackView.alignment = UIStackViewAlignment.leading
        stackView.axis = .vertical

    }

    //this is where the heavy logic, to create the dynamic radio buttons takes place
    func showQuestions(){

        if(questions.count <= 1){
            rootView.frame.size.height = 200
            nestedView.frame.size.height = 200
        }else{
            rootView.frame.size.height = 400
            nestedView.frame.size.height = 400
        }

        for question in questions{
            var otherButtons : [DLRadioButton] = []

            let frame1 = CGRect(x: self.view.frame.size.width / 2 - 131, y: 350, width: 262, height: 17);
            //we create a base radio button to use it as an anchor view
            let firstRadioButton = createRadioButton(frame: frame1, title: "", color: UIColor.purple);

            let label = UILabel()
            label.textAlignment = .center
            label.font = UIFont.boldSystemFont(ofSize: 17.0)
            label.textColor = UIColor.darkGray.withAlphaComponent(0.85)
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.25
            label.frame = CGRect(x: 0, y: 0, width: 200, height: 30)
            label.text = question.question

            self.stackView.insertArrangedSubview(label, at: self.indexView)

            self.indexView += 1
            let poll = Poll()
            poll.idQuestion = question.idQuestion

            var i = 0;
            for answer in question.answers{

                let frame = CGRect(x: self.view.frame.size.width / 2 - 131, y: 380 + 30 * CGFloat(i), width: 300, height: 17);
                let radioButton = createRadioButton(frame: frame, title: answer.answer! + " ", color: UIColor.purple)
                radioButton.tag = answer.idAnswer
                radioButton.params["poll"] = poll
                otherButtons.append(radioButton)
                self.stackView.insertArrangedSubview(radioButton, at: self.indexView)
                i += 1;
                self.indexView += 1
            }


            firstRadioButton.otherButtons = otherButtons
            firstRadioButton.isHidden = true
            firstRadioButton.otherButtons[1].isSelected = true

        }
    }

    //Method to create a custom button
    private func createRadioButton(frame : CGRect, title : String, color : UIColor) -> MyDLUIButton {
        let radioButton = MyDLUIButton(frame: frame);
        radioButton.titleLabel?.translatesAutoresizingMaskIntoConstraints = false
        radioButton.titleLabel!.font = UIFont.systemFont(ofSize: 14);
        radioButton.setTitle(title, for: []);
        radioButton.setTitleColor(UIColor.darkGray, for: []);
        radioButton.iconColor = color;
        radioButton.indicatorColor = color;
        radioButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left;
        radioButton.addTarget(self, action: #selector(QuestionsDialog.selectedAnswer(_:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(radioButton);

        return radioButton;
    }


    @objc func selectedAnswer(_ sender: MyDLUIButton){

        let poll = sender.params["poll"] as? Poll
        poll?.idAnswer = sender.tag


        if let row = self.polls.index(where: {$0.idQuestion == poll?.idQuestion}) {
            self.polls[row] = poll!
        }else{
            self.polls.append(poll!)
        }


        print("polls size: \(self.polls.count)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewDidDisappear(_ animated: Bool) {
        if(self.polls.count < self.questions.count){
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "questionsDialogDismissed"), object: nil)
        }
    }

    @IBAction func requestService(_ sender: UIButton) {
        delegate?.questionsAnswered(polls: self.polls)
    }

}

class  MyDLUIButton: DLRadioButton{
    var params: Dictionary<String, Any>
    override init(frame: CGRect) {
        self.params = [:]
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        self.params = [:]
        super.init(coder: aDecoder)
    }
}
导入UIKit
导入DLRadioButton
//委托管理投票
协议问题DialogDelegate:类{
func问题已回答(投票:[投票])
}
类问题对话框:UIViewController{
@IBVAR stackView:UIStackView!
@ibvar rootView:UIView!
@IBVAR嵌套视图:UIView!
弱var委托:问题DialogDelegate?
var问题:[问题]!
var polls=[Poll]()
var serviceType:Int=0
变量indexView:Int=0
重写func viewDidLoad(){
super.viewDidLoad()
//设置堆栈视图属性
stackView.alignment=UIStackViewAlignment.leading
stackView.axis=.vertical
}
//这就是创建动态单选按钮的重要逻辑所在
func showQuestions(){
如果(问题。计数MydLui按钮{
let radioButton=MyDLUIButton(帧:帧);
radioButton.titleLabel?.translatesAutoResizingMacSkinToConstraints=false
radioButton.titleLabel!.font=UIFont.systemFont(大小:14);
radioButton.setTitle(标题,用于:[]);
radioButton.setTitleColor(UIColor.darkGray,用于:[]);
radioButton.iconColor=颜色;
radioButton.indicatorColor=颜色;
radioButton.contentHorizontalAlignment=UIControlContentHorizontalAlignment.left;
radioButton.addTarget(自身,操作:#选择器(问题对话框。selectedAnswer(:)),用于:UIControlEvents.touchUpInside)
self.view.addSubview(单选按钮);
返回单选按钮;
}
@objc func selectedAnswer(uu发送方:MyDLUIButton){
让poll=sender.params[“poll”]as?poll
poll?.idAnswer=sender.tag
如果let row=self.polls.index(其中:{$0.idQuestion==poll?.idQuestion}){
self.polls[row]=投票!
}否则{
self.polls.append(poll!)
}
打印(“轮询大小:\(self.polls.count)”)
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
}
覆盖func VIEWDID消失(uu动画:Bool){
if(self.polls.count
我在网上找不到任何合适的答案,因此我正在分享我的代码,以便在swift中创建动态自定义单选按钮。 我希望这能对某些人有所帮助

这个区块显示了动态部分,但是我完全鼓励您从提供的链接下载完整的项目,以便您能够理解整个逻辑

import UIKit
import DLRadioButton

//Delegate to manage the Polls
protocol QuestionsDialogDelegate : class{
    func questionsAnswered(polls: [Poll])
}

class QuestionsDialog: UIViewController {

    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var nestedView: UIView!
    weak var delegate: QuestionsDialogDelegate?
    var questions : [Question]!
    var polls = [Poll]()
    var serviceType : Int = 0
    var indexView : Int = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        //setting the stack view properties
        stackView.alignment = UIStackViewAlignment.leading
        stackView.axis = .vertical

    }

    //this is where the heavy logic, to create the dynamic radio buttons takes place
    func showQuestions(){

        if(questions.count <= 1){
            rootView.frame.size.height = 200
            nestedView.frame.size.height = 200
        }else{
            rootView.frame.size.height = 400
            nestedView.frame.size.height = 400
        }

        for question in questions{
            var otherButtons : [DLRadioButton] = []

            let frame1 = CGRect(x: self.view.frame.size.width / 2 - 131, y: 350, width: 262, height: 17);
            //we create a base radio button to use it as an anchor view
            let firstRadioButton = createRadioButton(frame: frame1, title: "", color: UIColor.purple);

            let label = UILabel()
            label.textAlignment = .center
            label.font = UIFont.boldSystemFont(ofSize: 17.0)
            label.textColor = UIColor.darkGray.withAlphaComponent(0.85)
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.25
            label.frame = CGRect(x: 0, y: 0, width: 200, height: 30)
            label.text = question.question

            self.stackView.insertArrangedSubview(label, at: self.indexView)

            self.indexView += 1
            let poll = Poll()
            poll.idQuestion = question.idQuestion

            var i = 0;
            for answer in question.answers{

                let frame = CGRect(x: self.view.frame.size.width / 2 - 131, y: 380 + 30 * CGFloat(i), width: 300, height: 17);
                let radioButton = createRadioButton(frame: frame, title: answer.answer! + " ", color: UIColor.purple)
                radioButton.tag = answer.idAnswer
                radioButton.params["poll"] = poll
                otherButtons.append(radioButton)
                self.stackView.insertArrangedSubview(radioButton, at: self.indexView)
                i += 1;
                self.indexView += 1
            }


            firstRadioButton.otherButtons = otherButtons
            firstRadioButton.isHidden = true
            firstRadioButton.otherButtons[1].isSelected = true

        }
    }

    //Method to create a custom button
    private func createRadioButton(frame : CGRect, title : String, color : UIColor) -> MyDLUIButton {
        let radioButton = MyDLUIButton(frame: frame);
        radioButton.titleLabel?.translatesAutoresizingMaskIntoConstraints = false
        radioButton.titleLabel!.font = UIFont.systemFont(ofSize: 14);
        radioButton.setTitle(title, for: []);
        radioButton.setTitleColor(UIColor.darkGray, for: []);
        radioButton.iconColor = color;
        radioButton.indicatorColor = color;
        radioButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left;
        radioButton.addTarget(self, action: #selector(QuestionsDialog.selectedAnswer(_:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(radioButton);

        return radioButton;
    }


    @objc func selectedAnswer(_ sender: MyDLUIButton){

        let poll = sender.params["poll"] as? Poll
        poll?.idAnswer = sender.tag


        if let row = self.polls.index(where: {$0.idQuestion == poll?.idQuestion}) {
            self.polls[row] = poll!
        }else{
            self.polls.append(poll!)
        }


        print("polls size: \(self.polls.count)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewDidDisappear(_ animated: Bool) {
        if(self.polls.count < self.questions.count){
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "questionsDialogDismissed"), object: nil)
        }
    }

    @IBAction func requestService(_ sender: UIButton) {
        delegate?.questionsAnswered(polls: self.polls)
    }

}

class  MyDLUIButton: DLRadioButton{
    var params: Dictionary<String, Any>
    override init(frame: CGRect) {
        self.params = [:]
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        self.params = [:]
        super.init(coder: aDecoder)
    }
}
导入UIKit
导入DLRadioButton
//委托管理投票
协议问题DialogDelegate:类{
func问题已回答(投票:[投票])
}
类问题对话框:UIViewController{
@IBVAR stackView:UIStackView!
@ibvar rootView:UIView!
@IBVAR嵌套视图:UIView!
弱var委托:问题DialogDelegate?
var问题:[问题]!
var polls=[Poll]()
var serviceType:Int=0
变量indexView:Int=0
重写func viewDidLoad(){
super.viewDidLoad()
//设置堆栈视图属性
stackView.alignment=UIStackViewAlignment.leading
stackView.axis=.vertical
}
//这就是创建动态单选按钮的重要逻辑所在
func showQuestions(){
如果(问题。计数MydLui按钮{
let radioButton=MyDLUIButton(帧:帧);
radioButton.titleLabel?.translatesAutoResizingMacSkinToConstraints=false
radioButton.titleLabel!.font=UIFont.systemFont(大小:14);
radioButton.setTitle(标题,用于:[]);
radioButton.setTitleColor(UIColor.darkGray,用于:[]);
radioButton.iconColor=颜色;
radioButton.indicatorColor=颜色;
radioButton.contentHorizontalAlignment=UIControlContentHorizontalAlignment.left;
radioButton.addTarget(自身,操作:#选择器(问题对话框。selectedAnswer(:)),用于:UIControlEvents.touchUpInside)
self.view.addSubview(单选按钮);
返回单选按钮;
}
@objc func selectedAnswer(uu发送方:MyDLUIButton){
让poll=sender.params[“poll”]as?poll
poll?.idAnswer=sender.tag
如果let row=self.polls.index(其中:{$0.idQuestion==poll?.idQuestion}){
self.polls[row]=投票!
}否则{
self.polls.append(poll!)
}
打印(“轮询大小:\(self.polls.count)”)
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
}
覆盖func VIEWDID消失(uu动画:Bool){
if(self.polls.count