Reputation: 204
Is it possible to achieve this using swift
?
I would like to make many checkboxes inside an UIView
in swift
Upvotes: 2
Views: 12864
Reputation: 1024
Swift 4
let checkedImage = UIImage(named: "checked")! as UIImage
let uncheckedImage = UIImage(named: "unchecked")! as UIImage
@IBAction func tickavtion(_ sender: Any) {
if unchecked {
(sender as AnyObject).setImage(checkedImage, for: UIControlState.normal)
unchecked = false
}
else {
(sender as AnyObject).setImage(uncheckedImage, for: UIControlState.normal)
unchecked = true
}
}
Upvotes: 1
Reputation: 345
Simply add a UIButton on the board. Remove the text and add an image for a unselected(default) state and a selected state.
On the ViewController add an @IBAction for the function as follows:
@IBAction func check(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
Upvotes: 4
Reputation: 2540
You can easily create simple checkbox control in swift like these...
@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;
}
}
Upvotes: 1
Reputation: 214
UI button
uncheckedImage
for your button
for UIControlStateNormal
and a checkedImage
for your UIControlStateSelected
. Now on taps the button will change its image
and alternate between checked
and unchecked
image
.
Upvotes: 2
Reputation: 443
Use for loop to create multiple checkboxes and set the x position.Set tag for each to identify when tap.
Upvotes: 0
Reputation: 4096
Simple just check for the image loaded on button and take appropriate action see below code:
// declare bool
var unchecked = true
@IBAction func tick(sender: UIButton) {
if unchecked {
sender.setImage(UIImage(named:"checked.png"), forControlState: .Normal)
unchecked = false
}
else {
sender.setImage( UIImage(named:"unchecked.png"), forControlState: .Normal)
unchecked = true
}
}
Note:
checked
and unchecked
.Upvotes: 6
Reputation: 92
which kind of checkbox you intend to make? Multi-selection or radio btn? Have you tried doing it in OC? I advice you 1) to add the btns into an array after you initialized them. 2) In the touch event you traverse the btns to implement your logic.
Upvotes: 0