以编程方式在按钮上添加图像和文本

3
我想要通过编程在我的按钮(红色按钮)上添加一个带有图像和文本“查看详情”的功能... 图像位于按钮的左侧,文本位于右侧。
UIImage *img = [UIImage imageNamed:@"image.png"];
[aButton setImage:img forState:UIControlStateNormal];
aButton.backgroundColor=[UIColor redColor]; 
//[img release]; i am not sure i release it or not  
//[testBtn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];
// what the above lines  line work? 
[aButton setTitle:@"View Details" forState:UIControlStateNormal];

我看到了按钮,但不是红色的按钮...只有红色的角落...


请返回翻译后的文本:查看https://dev59.com/inE85IYBdhLWcg3wYSVk - Vincent Osinga
5个回答

6

您需要制作一个红色背景上带有文本的按钮图像,并将其设置为按钮的背景...

以下是在按钮上设置图像的代码:

[but1 setImage:[UIImage imageNamed:@"LeftBack.png"] forState:UIControlStateNormal];// 在按钮上设置图像。


1
USE buttonOBJ.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft

1

你能发一段创建按钮的代码吗?也许你有一个RoundRectButton,不妨试试CustomButton。


-1

由于内存问题,不建议使用imageNamed。最好像这样从文件中加载图像:

NSString *path = [[NSString alloc]  initWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], @"fileName.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
[path release], path = nil;

-1
NSString *path = [[NSString alloc]  initWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], @"fileName.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
[path release], path = nil;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接