Reputation: 3052
I have several buttons with titles 0 - 9 and in my custom UIButton class I want to be able to use a switch to check the button title. The buttons are created in the storyboard. The UIButton class looks like:
protocol NumpadDelegate: class {
func changeValue()
}
class NumpadButton: UIButton, NumpadDelegate {
let initial = String() // I want to assign the title of the button here
var alternative = String()
var change: Bool = false {
didSet {
let title = change ? alternative : initial
setTitle(title, forState: .Normal)
}
}
func changeValue() {
change = !change
}
}
Is there a way to do that or I'll have to programmatically create the buttons? I'm trying to limit the use of a custom UIButton class so I don't have to create one for each of my buttons.
EDIT:
As requested, the code of when the button is pressed:
@IBAction func buttonNumber(sender: UIButton) {
let value = sender.titleLabel!.text!
switch value {
case "C": orderLabel.text = ""
default: orderLabel.text = orderLabel.text.map { count($0) < 10 ? $0 + value : $0 } ?? value
}
if let check = orderLabel.text {
inputResult.removeAll(keepCapacity: false)
for index in 0..<items.count {
let id = items[index].id
if id.lowercaseString.hasPrefix(check.lowercaseString) {
inputResult += [items[index]]
}
}
numpadTableView.reloadData()
}
}
What I'm trying to do is, when I swipe the buttons I want their titles to change to an alternative String
i.e. button with title 1 will change to A and button with title 2 will change to B.
Upvotes: 0
Views: 99
Reputation: 114773
Instead of assigning your buttons to a 'referencing outlet' in Interface Builder, assign them to a 'referencing outlet collection' which you can declare as
@IBOutlet var buttons: [NumpadButton]
Upvotes: 2
Reputation: 6704
Don't know exactly what you're going for but here's an example where I've created outlets for each NumpadButton
and added them to an array
.
class ViewController: UIViewController {
@IBOutlet weak var button1: NumpadButton!
@IBOutlet weak var button2: NumpadButton!
@IBOutlet weak var button3: NumpadButton!
@IBOutlet weak var button4: NumpadButton!
var array: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
array.addObject(button1)
array.addObject(button2)
array.addObject(button3)
array.addObject(button4)
}
Each button has a title of either "1", "2", "3" or "4". Then you can check the title via a case statement like so:
override func viewWillAppear(animated: Bool) {
for item in array {
var button = item as! UIButton
switch button.currentTitle! {
case "1":
println("This button has title of 1")
case "2":
println("This button has title of 2")
case "3":
println("This button has title of 3")
case "4":
println("This button has title of 4")
default:
println("default case")
}
}
}
}
This would be one way you could use a case statement to access the titles of UIButtons
and then just adjust the application to whatever functionality you want (e.g. through an IBAction
, etc.).
Upvotes: 0