PDA

View Full Version : Custom UIButtons


evan
2011-02-07, 01:50
Hey guys, I would like to create a button that basically resembles a button on the home screen of an iPhone -- there's a rectangular image with a label underneath it, but the whole area containing them both is a button. How do I go about doing this? I'm just getting into customizing the UI stuff and am a bit swamped with everything I'm seeing online. Thanks!

evan
2011-02-07, 14:41
Alright here's what I got so far, and I think I'm close:


- (void)viewDidLoad {
[super viewDidLoad];

CGRect frame = CGRectMake(15.0, 15.0, 84.0, 60.0);
UIImage *buttonImage = [UIImage imageNamed:@"icon_news.png"];
UIButton *stopButton = [[UIButton alloc] initWithFrame:frame];
UIImageView *imageView = [[UIImageView alloc] initWithImage:buttonImage];
[stopButton addSubview:imageView];
[stopButton setTitle:@"News" forState:UIControlStateNormal];
[stopButton setTitleColor:[UIColor grayColor] forState:UIControlEventTouchDown];
stopButton.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
stopButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[stopButton setBackgroundColor:[UIColor clearColor]];
[self.view addSubview: stopButton];
}


The only problem with this is when the button is clicked, nothing happens to the picture! I want it grayed out (like what happens if you set it as the background... but then it stretches to the size of the button and I want the text to show up underneath the picture).

Here's how it shows up, and currently when clicked only the text changes color. (as I specify to gray)

http://farm6.static.flickr.com/5256/5425423735_5ce6e58f02_t.jpg

chucker
2011-02-07, 15:03
Instead of setting up your own UIImageView and adding it as a subview, it might be easier to use setBackgroundImage:forState: or setImage:forState:.

evan
2011-02-07, 15:16
When I use setImage:forState: it doesn't show the title. setBackgroundImage:forState: automatically fills the whole frame of the button, which is also not wanted.

chucker
2011-02-07, 15:28
Well you could change the image such that it covers the whole button and contains the border.

You could also use KVO to wait for the state to change to pressed:

[self.titleLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

Then add a method to your observer class:

observeValueForKeyPath:ofObject:change:context:

…and use it to replace the image accordingly.