2013-03-18 117 views
2

我使用下面的代碼來加載圖像是在上,下半部分是按鈕的標題,但只有圖像,這是爲什麼?有什麼好的建議,請告訴我們,謝謝UIButton設置圖像和標題

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 73, 44)]; 

    [myButton setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal]; 
    [myButton setImageEdgeInsets: UIEdgeInsetsMake(0,0,22,0)]; 

    [myButton setTitle:@"test" forState:UIControlStateNormal]; 
    [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
    [myButton setTitleEdgeInsets: UIEdgeInsetsMake(22,10,0,10)]; 

    [self.view addSubview:myButton]; 
+0

指該鏈接 http://stackoverflow.com/questions/1469474/setting-an-image-for-a-uibutton-in-code http://stackoverflow.com/questions/11717219/uibutton-image-text-ios – NANNAV 2013-03-18 04:16:38

回答

3

就可以實現通過這種方式這樣的效果也..嘗試這個::

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 73, 55)]; 
UIImage *img = [UIImage imageNamed:@"icon.png"]; 
UIImageView *imgVw = [[UIImageView alloc ] init]; 
imgVw.image = img; 
imgVw.frame = CGRectMake(myButton.frame.origin.x, myButton.frame.origin.y, myButton.frame.size.width, (myButton.frame.size.height-18)); 
[myButton setTitle:@"test" forState:UIControlStateNormal]; 
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
[myButton setTitleEdgeInsets: UIEdgeInsetsMake(34,10,0,10)]; 
[myButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:imgVw];  
[self.view addSubview:myButton]; 

你的按鍵方法

-(void) btnClick:(id)sender 
{ 
    NSLog(@"working"); 
} 

你也可以從你的邏輯中實現::在這裏我編輯了一些你的邏輯代碼

UIButton *myButton = [[UIButton alloc]initWithFrame:CGRectMake(160, 400, 40, 35)]; 
[myButton setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal]; 
[myButton setImageEdgeInsets:UIEdgeInsetsMake(0,(myButton.frame.size.width-52),17,0)]; 
[myButton setTitle:@"test" forState:UIControlStateNormal]; 
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
[myButton setTitleEdgeInsets: UIEdgeInsetsMake(22,(myButton.frame.size.width-78),0,22)]; 
[self.view addSubview:myButton]; 

但是,在這種邏輯中,您必須將圖像大小調整爲23 * 23像素。根據你的圖像尺寸UIEdgeInsetsMake的參數將被改變。

希望這會有所幫助。快樂的編碼。

+0

非常感謝! – user2090207 2013-03-18 07:17:57