Two buttons in two difference views, acting as a single button
I work on a project for iPhone iOS4 with Xcode 4.
My app uses a tabBar for two Views with two View Control开发者_运维知识库lers.
I want to programmatically create a Button in a View and to have same button in the other view.
For "same button" I mean that buttons have same background Image, same Title and so on. Also, when I programmatically change first button title also second button title change; same for backgrounds.
I was thinking something like "passing the pointer", but I do not know how to do it, how to pass a pointer from a View to another View. (I have a singleton GlobalData, if it can help.)
Thank you.
What you want to do is to create a custom UIButton, and then just use it wherever you need it. Once you change it in it's implementation file it will change globally.
Example CustomButton
//CustomButton.h
#import <UIKit/UIKit.h>
@interface CustomButton : UIButton{
}
@end
//CustomButton.m
#import "CustomButton.h"
@implementation CustomButton
- (id)init
{
self = [super init];
if (self) {
self.type = UIButtonTypeCustom;
self.frame = CGRectMake(170, 45, 150, 40);
[self setTitle:@"Title" forState:UIControlStateNormal];
[self.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:15]];
[self setBackgroundImage:[UIImage imageNamed:@"bg_image.png"] forState:UIControlStateNormal];
}
return self;
}
@end
Then use it like so:
#import "CustomButton.h"
...
CustomButton *myButton = [[CustomButton alloc] init];
Although the approach looks a bit shady, but I do not know what the use cases are so here it goes.
You can create a UIButton subclass and make that a singleton. Or store that in the AppDelegate.
An interesting thing to note is that when you add the same object to a second view, it will be removed from the first view! So you will have to keep adding it back to the view when ViewController's viewWillAppear: method is called.
精彩评论