Positioning Navigation Bar buttons in iOS 7 [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-12 10:27:31

问题


I am using custom image for navigation bar button.In iOS 6,if we set the left bar button item with button,its x value starts from 10px. But in iOS 7,if we do the same thing,x value of button starts at 20px. Is there any way we shall make it start from 10px as the buttons appearance is not so good with that in iOS 7?


回答1:


UIBarButtonItems can be initialized using initWithCustomView: method. So you can create some custom view (in your case navigation bar button item with custom image) and initialize bar button item with that custom view. Example:

    CustomView *view = [[CustomView alloc] initWithImage:[UIImage imageNamed:@"back.png"]];
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithCustomView:view];

You can set any frame you want in initWithImage: method of CustomView:

- (id)initWithImage:(UIImage *)image {
    self = [super initWithFrame:CGRectMake(0, 0, 50, 44)];

    CGRect backArrowFrame;


    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        backArrowFrame = CGRectMake(-8, 12, 12.5, 20.5);
    } else {
        backArrowFrame = CGRectMake(-2, 12, 12.5, 20.5);
    }

    UIButton *imView = [[UIButton alloc] initWithFrame:backArrowFrame];
    [imView setContentMode:UIViewContentModeScaleAspectFit];
    [imView setBackgroundImage:image forState:UIControlStateNormal];
    [imView addTarget:target action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:imView];


    return self;
}

In this way it is possible to change frame of UIBarButtonItem.




回答2:


No, you can't change the UIBarButtonItem frame. Instead, subclass UINavigationBar.




回答3:


Add button as navigation item in ios7 as below

UIButton *btnAdd = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];

[btnAdd setContentMode:UIViewContentModeScaleAspectFit];

[btnAdd setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];

[btnAdd addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *btnAdd = [[UIBarButtonItem alloc] initWithCustomView:imView];

self.navigationItem.rightBarButtonItem = btnAdd;


来源:https://stackoverflow.com/questions/19292742/positioning-navigation-bar-buttons-in-ios-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!