开发者

UIButton with Picture and Text

开发者 https://www.devze.com 2023-02-09 06:43 出处:网络
I\'m trying to make a button that basically mimics the buttons seen on the iphone\'s home screen - it has a picture placed vertically above some text, and both are part of the button and behave approp

I'm trying to make a button that basically mimics the buttons seen on the iphone's home screen - it has a picture placed vertically above some text, and both are part of the button and behave appropriately (dim, clickable, etc) when highlighted.

I've tried putting the picture or the text into its own f开发者_运维技巧rame but that doesn't work because whichever is in the new frame doesn't dim with the rest of the button.

Using the background image property doesn't work because I want the image above the text - the area behind the text should be transparent. I would REALLY prefer a programming solution instead of going in and editing all my pictures.


Create a subclass of UIView, and have a UIImageView and UILabel as subviews, and position them appropriately using code.

You'd then have the UIImageView and UILabel as properties so that you could access them, like this:

myCustomButton.imageView.image = [UIImage imageNamed:@"..."];
myCustomButton.textLabel.text = @"...";

Or you could probably find a 3rd Party custom UIView, on the internet on github or something.


Jonathan's idea is a good one, but if you're only doing it with a couple images it's not worth the trouble. You can create a UIImage and a UILabel and then place them inside a UIButton in interface builder.

Still, it's always a good idea to learn about powerful features like subclassing.

Good luck,

Aurum Aquila


do this:

UIButton *btn_chat = [UIButton buttonWithType:UIButtonTypeCustom];
btn_chat.frame = CGRectMake(40, 50, 100, 30);//CGRectMake(20, 20, 200, 72);
UIImage *image = [UIImage imageNamed:@"chat.png"];
CGSize newSize = CGSizeMake(30, 30);
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();
[btn_chat setImage:newImage forState:UIControlStateNormal];
btn_chat.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
[btn_chat setTitle:@"Chat" forState:UIControlStateNormal];
btn_chat.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
btn_chat.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[btn_chat addTarget:self action:@selector(menuSelection:) forControlEvents:UIControlEventTouchUpInside];
[btn_chat setTag:1001];
[self.view addSubview:btn_chat];

and it's done :)


Create a new initially transparent bitmap drawing context, draw your image to the top and text to the bottom. Then make a new image from this drawing context, and use that new image for the button.

0

精彩评论

暂无评论...
验证码 换一张
取 消