I have a rather basic question where I'm actually not sure whether it's a bug in UIKit
or intended behaviour.
It seems to be common agreement when declaring view properties in a UIViewController
which should be added to the view controller's subviews
and thus displayed on the screen, that these properties should be weak
.
The rationale behind this weak
declaration makes sense because the view controller already owns the subview through its subviews
property, so another strong reference wouldn't add any value here. This is also confirmed in many Stackoverflow posts, e.g. this one.
I am now running into an issue with UIButton
. When I want to add a button programmatically and first declare it as a property of a UIViewController
and then call [self.view addSubview:self.someButton]
, the button only shows up when it's declared as strong
, but not when being declared as weak
.
Here is the minimal example code to comprehend my issue:
@interface ButtonTestViewController ()
// only works with strong!
// when declared weak, no button appears on the screen and the
// logging output doesn't contain the button as a subview...
@property (nonatomic, strong) UIButton *someButton;
@end
@implementation ButtonTestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.someButton setCenter:self.view.center];
[self.view addSubview:self.someButton];
NSLog(@"subviews: %@", self.view.subviews);
}
- (UIButton *)someButton
{
if (!_someButton) {
UIButton *someButton = [UIButton buttonWithType:UIButtonTypeSystem];
CGRect someButtonFrame = CGRectMake(0.0, 0.0, 100.0, 44.0);
someButton.frame = someButtonFrame;
[someButton setTitle:@"Do something" forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(someButtonPressed) forControlEvents:UIControlEventTouchUpInside];
_someButton = someButton;
}
return _someButton;
}
- (void)someButtonPressed
{
NSLog(@"button pressed...");
}
@end
I also set up a small gist, where I also added another UI element (a UITextField
) next to the UIButton
for comparison. The UITextField
is also shown when being declared weak
. So, is this a bug in UIKit
or is there actually a reason why UIButton
s can't be declared weak
?