2015-02-09 31 views
0

我寫了下面的代碼爲我的應用程序:UIButton設置框架不工作?

self.PlayButton = [[UIButton alloc] init]; 

//Setup Play Button 
[self.PlayButton setTranslatesAutoresizingMaskIntoConstraints:NO]; 
self.PlayButton.frame = CGRectMake(self.view.frame.size.width * 0.38, self.view.frame.size.height * 0.666, self.view.frame.size.width * 0.48, self.view.frame.size.height * 0.29); 
[self.PlayButton setBackgroundImage:[UIImage imageNamed:@"PlayButton.png"] forState:UIControlStateNormal]; 
[self.PlayButton.layer setMagnificationFilter:kCAFilterNearest]; 
[self.PlayButton addTarget:self action:@selector(PlayButtonMethod) forControlEvents:(UIControlEvents)UIControlEventTouchUpInside] 


[self.view addSubview:self.PlayButton]; 

但是,當這個代碼運行它,而不是出現在它只是出現在視圖的左上角一個相當具體位置的圖像。幾乎像它已被設置

self.PlayButton.frame = CGRectMake(0, 0, self.view.frame.size.width * 0.48, self.view.frame.size.height * 0.29); 

因爲寬度和高度被放在正確的,但無論出於何種原因由CGRectMake設置按鈕的位置沒有考慮到這是奇怪的。我已經做了一些關於在代碼中創建UIButtons的研究,而且從我看到的情況來看,不僅這些發生在其他人身上,代碼編寫完全負有責任。

任何幫助,將不勝感激。 謝謝

+0

我的第一個猜測是它是一個自動佈局問題。至於如何解決它我不確定,但你可能想嘗試做initWithFrame:看看是否有所作爲。 – 2015-02-10 01:25:35

+0

@SkylerLauren剛剛給了一個嘗試,沒有什麼區別:/這個問題真的讓我失望......它發生在我所有的3個按鈕上。 – OllysEdits 2015-02-10 13:59:12

回答

1

看起來像ive發現修復: 刪除這行代碼解決了我的問題。

[self.PlayButton setTranslatesAutoresizingMaskIntoConstraints:NO]; 

不是100%確定爲什麼這是導致問題,但它修復了它。

+0

當您使用約束來定義佈局時,將其設置爲NO。我沒有嘗試過,但是我懷疑當你將它設置爲NO,並且不設置約束時,你會得到你描述的行爲。 – narco 2016-08-06 13:19:06

0

使用標準alloc init方法創建UIButton時,實際上並沒有創建按鈕。創建和初始化UIButton的方法稱爲buttonWithType:。這將創建指定類型的UIButton,如果您使用alloc init它將無法正常工作,請參閱Apple Documentation for UIButton

所以,你需要更改線路

self.PlayButton = [[UIButton alloc] init]; 

self.PlayButton = [UIButton buttonWithType:UIButtonTypeCustom]; 

buttonWithType:讓您在UIButtonType枚舉傳遞,因此將接受任何以下值:

  • UIButtonTypeCustom
  • UIButtonTypeSystem
  • UIButtonTypeDetailDisclosure
  • UIButtonTypeInfoLight
  • UIButtonTypeInfoDark
  • UIButtonTypeContactAdd
  • UIButtonTypeRoundedRect

如果不傳遞一個UIButtonType按鈕將不會被初始化,因爲它不知道什麼類型的你想要的按鈕,它不會假設。還檢查了Apple Documentation for UIButtonType

旁註

我只是要包括這個作爲一個方面說明。因爲我注意到您正在使用大寫字母來啓動您的變量名稱(即PlayButton),所以請仔細閱讀Apple Coding Conventions Documentation。變量名稱應該以小寫字母開頭(即playButton),而Class和Enum名稱應該以大寫字母開頭。UIViewController)。遵守約定總是很好的,因爲它使你的代碼更具可讀性和可維護性,所以如果另一個開發人員來修改你的代碼,他們甚至你自己都很容易閱讀。