How make radio buttons in swift 3

2019-03-01 12:11发布

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 my problem but it's show only Horizontal way direction(side by side direction), I need vertical ways(i.e Display one radio button after below another radio button) . Any guidance will be appreciated. Thank you in advance.

Link : https://github.com/sag333ar/SKRadioButton

标签: ios swift3
4条回答
放我归山
2楼-- · 2019-03-01 12:35

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.

查看更多
Animai°情兽
3楼-- · 2019-03-01 12:45

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.

enter image description here

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

enter image description here

Change the Alignment from Storyboard Like this.

enter image description here

That's it here is Your Output:

enter image description here

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-01 12:47

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

查看更多
再贱就再见
5楼-- · 2019-03-01 12:54

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.

查看更多
登录 后发表回答