Правильный способ добавить заголовок на панель инструментов контроллера модального представления? - PullRequest
8 голосов
/ 24 августа 2009

Прямо сейчас я использую это в моем -viewDidLoad методе:

UIToolbar *toolbar = [[UIToolbar alloc] init];

UIBarButtonItem *flexibleSpace = [UIBarButtonItem alloc];
flexibleSpace = [flexibleSpace initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                    target:nil
                                                    action:nil];

// Add a back button to allow user to close the modal view
NSString *back = NSLocalizedString(@"Back", nil);
UIBarButtonItem *backButton = [UIBarButtonItem alloc];
backButton = [backButton initWithTitle:back
                                 style:UIBarButtonItemStyleDone
                                target:self
                                action:@selector(dismissModalViewControllerAnimated:)];

// Add a centered title to the toolbar

// I doubt this is the "correct" way to do this, but it seems to work.
// The "width" property of a UIBarButtonItem doesn't seem to correspond to
// the actual width if the button is flexible (i.e. the width isn't explicitly
// set), so I'm using this hack instead.
// This is obviously NOT an optimal solution. For one thing, if the button padding
// ever changes, it has to be changed manually here as well. For another, it is
// a pain to do this for every button I add to the toolbar, and furthermore the title
// is centered only according to its own width, not the toolbar's.
const CGRect toolbarFrame = [toolbar frame];
const CGFloat backWidth = [back sizeWithFont:[UIFont boldSystemFontOfSize:[UIFont buttonFontSize]]
                           constrainedToSize:toolbarFrame.size].width;

const CGRect titleFrame = {{0.0f, 0.0f},
                           {toolbarFrame.size.width - (backWidth * 2.0f), 50.0f}};
UILabel *titleLabel = [[UILabel alloc] initWithFrame:titleFrame];
[titleLabel setText:[self title]];
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setTextAlignment:UITextAlignmentCenter];
[titleLabel setFont:[UIFont boldSystemFontOfSize:20.0f]];
[titleLabel setTextColor:[UIColor whiteColor]];
[titleLabel setShadowColor:[UIColor colorWithWhite:0.0f alpha:0.5f]];
[titleLabel setShadowOffset:CGSizeMake(0.0f, -1.0f)];

UIBarButtonItem *titleItem = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
[titleLabel release];

NSArray *items = [[NSArray alloc] initWithObjects:flexibleSpace, titleItem, backButton, nil];
[flexibleSpace release];
[titleItem release];
[backButton release];

[toolbar setItems:items];
[items release];

[view addSubview:toolbar];
[toolbar release];

У кого-нибудь есть лучший способ сделать это? То, что я использую, похоже на серьезный взлом: (.

Edit:

Спасибо за предложение, Даррен!

Вот что я сейчас использую, если кому-то интересно:

Во-первых, в соответствии с предложением Даррена, я оборачиваю свой контроллер модального представления в универсальный UINavigationController (который содержит собственный UIToolbar, UINavigationBar, который идет с заголовком):

MyCustomViewController *myModalViewController = [[MyModalViewController alloc] init];
[myModalViewController setTitle:@"Foo"];

UINavigationController *modalNavController = [[UINavigationController alloc] initWithRootView:myModalViewController];
[myModalViewController release];

// This is intended to be presented in another view controller class
[self presentModalViewController:modalNavController animated:YES];
[modalNavController release];

Тогда в моем -init методе для класса MyModalViewController у меня есть это:

- (id)init
{
    if (self = [super init]) {
        UIBarButtonItem *backButtonItem = [UIBarButtonItem alloc];
    backButtonItem = [backButtonItem initWithTitle:back
                                                     style:UIBarButtonItemStyleDone
                                                    target:[self navigationController]
                                                    action:@selector(dismissModalViewControllerAnimated:)];
        [[self navigationItem] setRightBarButtonItem:backButtonItem];
        [backButtonItem release];
    }
    return self;
}

Это намного более чистое решение, чем раньше. Спасибо.

Ответы [ 2 ]

10 голосов
/ 24 августа 2009

Вы должны обернуть свой контроллер вида в общий UINavigationController при представлении модального вида:

MyCustomController* myController = [[MyCustomController alloc] init];
editor.title = @"My Title";

UINavigationController* modalController = [[UINavigationController alloc] initWithRootViewController:myController];
[self.navigationController presentModalViewController:modalController animated:YES];

[modalController release];
[myController release];

Ваш пользовательский контроллер может указывать кнопки панели инструментов в методе init:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel 
                                                                                               target:self 
                                                                                               action:@selector(doCancel:)] autorelease];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                                                target:self 
                                                                                                action:@selector(doSave:)] autorelease];
    }
    return self;
}
1 голос
/ 24 августа 2009

Вы должны добавить заголовок в свойство items

т.е.

@property(nonatomic, copy) NSArray *items 

где элементы инициализированы с заголовком

initWithTitle:style:target:action:

См. http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIToolbar_Class/Reference/Reference.html#//apple_ref/occ/instp/UIToolbar/items

и

http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIBarButtonItem_Class/Reference/Reference.html#//apple_ref/occ/instm/UIBarButtonItem/initWithTitle:style:target:action:

для деталей.

Надеюсь, что поможет

[Изменить] Постскриптум UIBarButtonItem также там, где вы будете добавлять свои кнопки ;-)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...