2

bar buttonすべてのクラスでを作成しています。このコードを一度だけ記述して、すべてのクラスで使用する方法はありますか?

 toolbar = [[UIToolbar alloc]
               initWithFrame:CGRectMake(90, 0, 100, 45)];
    toolbar.tintColor=self.navigationController.navigationBar.tintColor;

    // create an array for the buttons
    NSMutableArray* buttonsArray = [[NSMutableArray alloc] initWithCapacity:2];

    // create a standard save button

    UIImage *buttonImage = [UIImage imageNamed:@"home.png"];

    UIButton *homeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [homeButton setImage:buttonImage forState:UIControlStateNormal];


    homeButton.frame = CGRectMake(100,2, 35, 35);

    [homeButton addTarget:self action:@selector(homeButtonpress) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *customHomeBarItem = [[UIBarButtonItem alloc] initWithCustomView:homeButton];

    [buttonsArray addObject:customHomeBarItem];
    [customHomeBarItem release];


    UIImage *logoutImg=[UIImage imageNamed:@"power.png"];

    UIButton *logOutBtn=[UIButton buttonWithType:UIButtonTypeCustom];

    [logOutBtn setImage:logoutImg forState:UIControlStateNormal];

    [logOutBtn addTarget:self action:@selector(logOutButtonPress) forControlEvents:UIControlEventTouchUpInside];


    logOutBtn.frame=CGRectMake(0, 2, 35, 40);


    UIBarButtonItem *customLogOutButton=[[UIBarButtonItem alloc]initWithCustomView:logOutBtn];

    [buttonsArray addObject:customLogOutButton];
    [customLogOutButton release];


    [toolbar setItems:buttonsArray animated:NO];
    [buttonsArray release];

    // place the toolbar into the navigation bar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];
    [toolbar release];
4

1 に答える 1

3
  1. ユーティリティ クラスを作成する
  2. UIBarButtonItem を作成して返すためのクラス メソッドを追加します。
  3. Utility.h を .pch または使用するクラスにインポートします。

ユーティリティ.m

+ (UIBarButtonItem *) barButtonItemWithTitle:(NSString *)title backgroundImage:(NSString *)image target:(id)target action:(SEL)action
{
    //create button & return it
    return barButtonItem;
}

使用するには

ViewController.m

    UIBarButtonItem* backButtonItem = [Utility barButtonItemWithTitle:@" Back" backgroundImage:@"back_button" target:self action:@selector(backButtonAction)];
    self.navigationItem.leftBarButtonItem = backButtonItem;
于 2013-01-18T07:43:03.633 に答える