【问题标题】:Creating a common UIToolbar helper file and methods for Objective C为 Objective C 创建一个通用的 UIToolbar 帮助文件和方法
【发布时间】:2011-09-30 16:50:28
【问题描述】:

我用 UIToolbar 构建了一个视图,效果很好。

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

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

我试过把下面的代码放到一个.h.m文件中并继承自UIView,但是有一个问题,因为有对self.navigiationItem的引用

有没有一种方法可以创建一个通用的 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");
    }

【问题讨论】:

    标签: objective-c dry helper uitoolbar


    【解决方案1】:

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

    【讨论】:

    • 啊,我试试看能不能解决问题。我相信它会的。我仍然可以将 IBActions 移动到这些新的帮助文件吗?谢谢。
    猜你喜欢
    • 2012-04-10
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2018-01-13
    相关资源
    最近更新 更多