为Objective C创建一个通用的工具栏帮助文件和方法



我已经建立了一个视图与UIToolbar工作得很好。

这个工具栏将出现在整个应用程序,现在我复制/粘贴代码到许多不同的文件。

我不想重复自己,我希望创建一个助手文件,将包括工具栏设置和方法链接到我需要的每个文件的工具栏。

我试过把下面的代码放入一个。h .m文件,并从UIView继承,但有一个问题,因为有一个引用self. navigationitem

是否有一种方法,我可以创建一个共同的Objective C文件,将有所有的代码和方法,我想使用?

谢谢。

- (void)viewDidLoad
   // ... 
    // appears in viewDidLoad
     // ---- TOOLBAR -----------//
        UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 100.0, 44.01f)];
        //[toolbar setBackgroundColor:[UIColor blackColor]];
        //[toolbar setTintColor:[UIColor redColor]];
        //[toolbar.layer setBorderColor:[[UIColor redColor] CGColor]];
        // Bar buttons
        UIBarButtonItem *barReloadBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(btnReload:)];
        [barReloadBtn setStyle:UIBarButtonItemStyleBordered];
        // Profile bar button
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"111-user" ofType:@"png"]];
        UIBarButtonItem *barProfileBtn = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(btnProfile:)];

        // Button array
        NSMutableArray *buttons = [[NSMutableArray alloc] init]; 
        [buttons addObject:barProfileBtn];
        [buttons addObject:barReloadBtn];

        [toolbar setItems:buttons];
        // Set nav items
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];
        // memory cleanup
        [image release];
        [buttons release];
        [barReloadBtn release];
        [barProfileBtn release];    
        [toolbar release];

        // ---- /TOOLBAR -----------//
    }

    #pragma mark - IBActions
    -(IBAction) btnProfile:(id)sender
    {
        UserProfileVC *userProfileVC = [[UserProfileVC alloc] initWithNibName:@"UserProfileVC" bundle:[NSBundle mainBundle]];
        UINavigationController *tmpNavCon = [[UINavigationController alloc] initWithRootViewController:userProfileVC];
        [self.navigationController presentModalViewController:tmpNavCon animated:YES];
        [tmpNavCon release];
        [userProfileVC release];
    }
    -(IBAction) btnReload:(id)sender
    {
        NSLog(@"Not done yet");
    }

navigationItemUIViewController的性质,而不是UIView的性质。如果你有这样的常见功能,我会从UIViewController继承,将您的自定义逻辑添加到viewDidLoad(或任何合适的地方),然后从该类继承您的视图控制器。只要确保从viewDidLoad的子类实现中调用[super viewDidLoad]即可。

最新更新