How make radio buttons in swift 3

后端 未结 4 1763
闹比i
闹比i 2021-01-23 00:03

I am creating a Swift iOS app in which I have to show a Radio Buttons which accepts Horizontal and Vertical ways. I have found one library at GitHub which looks the solution of

相关标签:
4条回答
  • 2021-01-23 00:39

    The link you share already can make vertical buttons , in usage it describes using it inside a horizontal UIStackView

    0 讨论(0)
  • 2021-01-23 00:47

    You can add multiple buttons with-in UIStackView, Then set the axis property of UIStackView to horizontal or vertical as per your requirement. To make the Radio button set the image of button & give title, then set the left title inset to make some space between button image & title.

    0 讨论(0)
  • 2021-01-23 00:48

    For this Simple thing can't need to use any Third-party Library you can Do it by Using UIButton Like this.

    import UIKit
    
    class RootViewController: UIViewController {
    
    @IBOutlet weak var btnMale: UIButton!
    @IBOutlet weak var btnFemale: UIButton!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
    
    @IBAction func btnTapped(_ sender: UIButton) {
    
        if sender.currentImage == UIImage(named: "radio_unchecked"){
    
            sender.setImage(UIImage(named: "radio_checked"), for: .normal)
    
        }else{
    
            sender.setImage(UIImage(named: "radio_unchecked"), for: .normal)
        }
    }
    

    In Storyboard Drag and Drop Two UIButton Connect its IBOutlet and then Connect with Same Action Outlet to Both Button.

    Add images, and one more thing Button Title set with Adding Before Space Like this.

    Change the Alignment from Storyboard Like this.

    That's it here is Your Output:

    0 讨论(0)
  • 2021-01-23 00:51

    Here is less code solution I believe!

    @IBOutlet weak var btn1: UIButton!
    @IBOutlet weak var btn2: UIButton!
    .
    .
    .
    .
    @IBOutlet weak var btn10: UIButton!
    
    
    var arrButtons:[UIButton] = []
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            arrButtons.append(btn1)
            arrButtons.append(btn2)
            //so, on
        }
    

    Go to button property and set state Config property selected image for UIButton so, it will replace image when isSelected property is true.

    Also Bind touchUpInside event to every buttons with "btnRadioPrressed" method.

        @IBAction func btnRadioPrressed(sender: UIButton) {
    
            for btn in arrButons {
                btn.isSelected = false
            }
            if let index = arrButons.index(where: { $0 == sender }) {
                arrButons[index].isSelected = true
            }
        }
    

    Hope this will help you with less code.

    0 讨论(0)
提交回复
热议问题