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
The link you share already can make vertical buttons , in usage it describes using it inside a horizontal UIStackView
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.
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:
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.