I'm trying to create round buttons for a custom number pad. I want to find and modify all the buttons via this fast enumeration loop:
for (UIView *subview in self.view.subviews)
{
if ([subview isKindOfClass:[UIButton class]])
{
NSLog(@"found a button!");
subview.layer.borderWidth = 1.0f;
subview.layer.borderColor = [[UIColor whiteColor] CGColor];
[subview.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
Doesn't work.
So I looked around and found this question. However, even though my method appears to follow the approach outlined in the accepted answer, the if
statement doesn't find buttons. The other answer on the page looked overly complicated for my needs.
Can someone please show me where I'm going wrong?
Edit
In response to @luk2303's comment:
I believe all the relevant buttons are indeed directly in view
. Here's a screenshot of the hierarchy in the storyboard:
2nd edit
Per @tomer's suggestion, I modified the code:
for (UIControl *subview in self.view.subviews)
{
NSLog(@"inside loop");
if ([subview isKindOfClass:[UIButton class]])
{
subview.layer.borderWidth = 1.0f;
subview.layer.borderColor = [[UIColor whiteColor] CGColor];
[subview.layer setCornerRadius: subview.frame.size.width/2.0f];
NSLog(@"button.tag = %ld", (long)subview.tag);
}
}
Unfortunately, no improvement in the result.
3rd edit
Here is a printout of the subviews, which obviously doesn't included the desired buttons...
2016-06-12 14:27:10.352 appName[5983:3143970] <_UILayoutGuide: 0x12f6912b0; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x12f691020>>
2016-06-12 14:27:19.419 appName[5983:3143970] <_UILayoutGuide: 0x12f6918b0; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x12f691a30>>
2016-06-12 14:27:21.988 appName[5983:3143970] <UIImageView: 0x12f691040; frame = (516 209; 49 49); autoresize = RM+BM; layer = <CALayer: 0x12f6911f0>>
According to your screenshot you already have them in storyboard, so you don't need to "find" them, they're here.
Do the following :
Link all buttons to your .h file by drag & dropping from the storyboard to the .h file, using right clic or ctrl+clic. Just like if you wanted to create an outlet. (by opening the Assistant editor, the middle button on the top right of the screen).
Once Xcode asks you if you want to add Outlet, or Outlet collection, or Action, chose "Outlet Collection", and name it "AllButtons" for example.
Repeat that process for every single button, except that instead of creating a new outlet collection, link every button to that recently-created outlet collection.
Now all your buttons are a part of that collection, or array if you will.
From your .m file, you can use the property and loop on it, just like you're doing with your subviews.
foreach (UIButton *button in AllMyButtons){
// Do your stuff here.
}
That's it. That's all there is to it :)