简体   繁体   中英

UIButton is nil after init

I am trying to create a UIButton - this works fine when I am using the simulator, but when I try on a device the button does not appear.

[self.followButton setImage:[UIImage new] forState:UIControlStateNormal];
[self.followButton setTitle:@"EDIT" forState:UIControlStateNormal];
self.profMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *icon = [[UIImage imageNamed:@"More"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[self.profMoreButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
[self.profMoreButton setImage:icon forState:UIControlStateNormal];
[self.profMoreButton.imageView setTintColor:[UIColor Primary]];
[self.profMoreButton addTarget:self action:@selector(morePressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.profMoreButton];
[self.profMoreButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.equalTo(self.followButton.mas_height).multipliedBy(0.6);
    make.centerY.equalTo(self.followButton);
    make.left.equalTo(self.followButton.mas_right).with.offset(8);
}];
if (!self.profMoreButton) {
    NSLog(@"WHY!?????");
}

On my iPhone 6 the NSLog at the end is always printed and the button doesnt appear UNLESS I put a breakpoint at the top and step my way through.

self.profMoreButton was declared as a weak IBOutlet, I removed the IBOutlet and changed it to strong. Now it works 😳

I THINK YOU DONT GIVEN ALLOC UIBUTTON

settingsButton =[UIButton buttonWithType:UIButtonTypeCustom];
settingsButton.frame= CGRectMake(SCREEN_WIDTH-[UIImage imageNamed:@"setting.png"].size.width-30, 22, [UIImage imageNamed:@"setting.png"].size.width, [UIImage imageNamed:@"setting.png"].size.height);
[settingsButton setImage:[UIImage imageNamed:@"setting.png"] forState:UIControlStateNormal];
[settingsButton addTarget:self action:@selector(settingButtonMethod) forControlEvents:UIControlEventTouchUpInside];
[settingsButton setMultipleTouchEnabled:NO];
settingsButton.exclusiveTouch=YES;
settingsButton.backgroundColor=CLEAR_COLOR;
[self.view addSubview:settingsButton];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM