我有下面的代碼基本上只是初始化一個UIButton。與更改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];
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];
當我按我想的按鈕背景要更改的按鈕,這樣的目標,我有以下:
- (void) button
{
[self setSelectedViewController:[self.viewControllers objectAtIndex:1]];
[self setTabBarWithImage:[UIImage imageNamed:@"Map-Profile.png"]];
}
的問題是,當應用程序第一最初加載,我必須按兩次按鈕才能使背景更改..爲什麼會這樣?第一次點擊按鈕時,這不會改變按鈕背景圖像。任何想法?
如果我是正確的,setBackgroundImage:forState:方法是一種配置方法,所以在初始化UIButton時設置一次就足以讓它爲所有聲明的狀態更改圖像。此外,永遠不要使用alloc init的setter,它會執行一個雙重初始化,這會導致一個泄漏,或者你可以設置一個autorelease UIButton來避免泄漏。 (self.button = [[[UIButton alloc] init] autorelease]; –
你似乎是在選擇器中設置了「UIControlStateNormal」的「Selected」圖像,默認的UIButton並沒有真正的選擇功能 什麼是它你希望發生? – EricLeaf
所以按鈕的初始背景顏色是紅色,當我點擊我希望它是藍色和藍色.. – adit