2012-07-11 38 views
0

好吧,夥計,UIButton with resizable圖片

我知道我做錯了什麼,但我無法弄清楚。這裏是代碼,將 把正常按鈕狀態的可調整大小的圖像。

self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44); 
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)]; 
    [self.loginButton setImage:image forState:UIControlStateNormal]; 
    [self addSubview:self.loginButton]; 

這裏是圖像

enter image description here

任一圖像的資產是錯誤或代碼。

圖像的寬度爲21px。 右上角的10,& 10左側1Px調整大小。

做任何一個地方我做錯了什麼。

感謝所有通過 阿倫

+0

你確定'image'不是'nil'? – 2012-07-11 01:04:18

+0

是的,我檢查它。都很好。 – 2012-07-11 01:05:39

+0

http://i.imgur.com/jpj1l.png這是它的外觀。 – 2012-07-11 01:05:56

回答

10

阻止你應該這樣來做:

self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44); 
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)]; 
    [self.loginButton setBackgroundImage:image forState:UIControlStateNormal]; 
[self.view addSubview:self.loginButton]; 

這樣,你要設置按鈕的背景圖像屬性。背景圖像已經附加到按鈕視圖,所以不需要添加子視圖。

+0

我真的很抱歉。我實際上是爲按鈕狀態設置圖像。 – 2012-07-11 01:15:10

+0

沒問題,但是您發佈的圖片似乎是背景圖片。如果您製作UIButtonTypeCustom,則該按鈕不會有背景。如果您想製作一個樣式化的按鈕,將該圖片作爲背景,您應該使用我發佈的代碼。 – tomidelucca 2012-07-11 01:23:55

+0

代碼與實際代碼有何不同? – 2012-07-11 01:33:00

0

嘗試

self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44); 
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]; //assuming the height is 44 
    [self.loginButton setImage:image forState:UIControlStateNormal]; 
    [self addSubview:self.loginButton]; 
+0

同樣的結果。但是在iOS 5.0中不推薦使用stretchableImageWithLeftCapWidth方法。所以它不是一個好主意。 – 2012-07-11 01:31:21