UIButton设置图像和标题
问题描述:
我使用下面的代码来加载图像是在上,下半部分是按钮的标题,但只有图像,这是为什么?有什么好的建议,请告诉我们,谢谢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];
答
就可以实现通过这种方式这样的效果也..尝试这个::
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
指该链接 http://*.com/questions/1469474/setting-an-image-for-a-uibutton-in-code http://*.com/questions/11717219/uibutton-image-text-ios – NANNAV 2013-03-18 04:16:38