issue with changing UIButton background image
I have the following code which basically just initialize a UIButton.
self.button = [[UIButton alloc] init];
self.button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
self.button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[self.voteSpot setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.voteSpot setBackgroundImage:[UIImage imageNamed:@"MainButton-Selected.png"] forState:UIControlStateSelected];
[self.button addTarget:self action:@selector(button) forControlEvents:UIControlEventTouchUpInside];
开发者_如何学Python CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height;
if (heightDifference < 0)
self.button.center = self.tabBar.center;
else
{
CGPoint center = self.tabBar.center;
center.y = center.y - heightDifference/2.0;
self.button.center = center;
}
[self.view addSubview:self.button];
When I press on the button I want the button background to be changed, so in the target I have the following:
- (void) button
{
[self setSelectedViewController:[self.viewControllers objectAtIndex:1]];
[self setTabBarWithImage:[UIImage imageNamed:@"Map-Profile.png"]];
}
The issue is that when the app first initially loads, I have to press the button twice to make the background change.. why is this? the first time I tap the button this doesn't change the button background image. Any idea?
I'm not sure what the problem is, but I'd start by creating the button using +buttonWithType
instead of +alloc
and -init
. The buttonType
property is read only, and initializing the button with -init
doesn't let you set the type.
You should set the highlighted/selected backgrounds before the user can tap the button. In other words, move the first two lines from the action method to where you create the button.
精彩评论