Reputation: 611
How can I set properties to an "extension" of an "IBOutletCollection" containing "UIButtons"? I am trying to do this in a similar way that one can do with an extension UIButton, that does not seem to extend to a collection of UIButtons. I hope to be as thorough and clear as possible.
Although there are similar questions:
1.Change the color of UIButton in IBOutletCollection
2.Set Individual Title of UIButtons in IBOutletCollection
...and numourous others. I still am not grasping how to do this, and can really use help that any of you can provide.
Here is what I have gathered so far:
Here is my code example: ( I have tried replacing where “Array” is with: “NSArray” & “Collection” with “Collection” working similar to “Array”)
//Inside the main viewController:
@IBOutlet var ButtonCollection: [UIButton]!
//Inside the extention file:
extension Array where Element == UIButton
{
func sharedButtonProperties()
{
for button in ButtonCollection
{
self.setTitleColor(.red, for: .normal)
//MARK: More properties will go here, once I get this to work.
}
}
}
//calling the code inside main viewController, within "viewDidAppear"
ButtonCollection.sharedButtonProperties()
Now here is an example of an extension of a single IBOutlet of a UIButton that is working just fine, but not with a Collection:
//Inside the main viewController:
@IBOutlet weak var ButtonSingle: UIButton?
//Inside the extention file:
extension UIButton
{
func buttonProperties()
{
self.setTitleColor(.red, for: .normal)
}
}
//calling the code inside main viewController, within "viewDidAppear"
ButtonSingle?.buttonProperties()
I am not an expert coder for sure, any help provided is greatly appreciated.
Thank you.
Upvotes: 0
Views: 229
Reputation: 611
I have finally found the solution after so much trial and error. I want to share the answer with anybody that needs to set properties to UIButtons within an IBOutletCollection. This is a very efficient way to cut down time when you want to set/define properties to a group of buttons, or to all buttons project-wide.
I really hope someone finds this useful!
Code (Tested & Works): Note that what is in bold is what changed from the code I had in question.
//Inside the main viewController
@IBOutlet var ButtonCollection: [UIButton]!
//Inside the extention file:
extension Array where Element == UIButton
{
func sharedButtonProperties()
{
for **buttonGrp** in **self**
{
**buttonGrp**.setTitleColor(.red, for: .normal)
//MARK: More properties will go here now!
}
}
}
//calling the code inside main viewController, within "viewDidAppear"
ButtonCollection.sharedButtonProperties()
As you can see: I almost had it figured out, but all that was needed was to call the “buttonGrp” for the “for-in-loop", and to set this in “self”. I hope that makes sence!
Bye bye!
Upvotes: 0