简体   繁体   中英

Subclassing UIView/UIViewController

I need a lot of custom buttons in my app. At the moment I'm using storyboard to define these buttons on every controller that I need. However, I feel that since I need them throughout my app, I'm better off putting in a different view controller/view that subclasses UIView or UIViewController so if I need to make any changes I will just have to do them once as opposed to in different view controllers. What would be the best way to do this? Also can you tell me how can I create buttons programatically? This is what I'm doing at the moment, and I'm getting a completely blank screen.

-(void)viewDidAppear:(BOOL)animated 
{ 
    UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [testButton setFrame:CGRectMake(0, 390, 100, 40)];
    [testButton setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
    [setImage:[UIImage imageNamed:@"test_button"] forState:UIControlStateNormal];
    [setImage:[UIImage imageNamed:@"test_button"] forState:UIControlStateHighlighted];  
    [setEnabled:YES];
    [self.view addSubview:testButton];
 }

there is a chance that your button is way off the visible rect. for adding the button programmatically, you are doing it mostly right. also, images should have the file extension. since you are adding a customButton, if there are no images, then you wont see any button. Try adding a title to your button, which would show up even if there is no image added.

try the code below.

-(void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; //you must have a good reason to not add this line.
    UIButton *testButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [testButton setFrame:CGRectMake(0, 20, 100, 40)];
    [testButton setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
    [testButton setImage:[UIImage imageNamed:@"test_button.png"] forState:UIControlStateNormal];
    [testButton setImage:[UIImage imageNamed:@"test_button.png"] forState:UIControlStateHighlighted]; 
    [testButton setEnabled:YES];
    [self.view addSubview:testButton];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM