简体   繁体   中英

iOS Set Size of Button in title of UINavigationBar

I am trying to use a button in place of the title on a UINavigationBar. I have been successful in getting the button to display with a custom image, but I am having a hard time figuring out how to resize it. I have tried a few things, including:

UIButton *titleButton = [[UIButton alloc]init];
UIImage *settingsButtonImage = [UIImage imageNamed:@"settingsButton2X.png"];
[titleButton addTarget:self action:@selector(settingsButtonPress:) forControlEvents:UIControlEventTouchDown];
[titleButton setBackgroundImage:settingsButtonImage forState:UIControlStateNormal];
[titleButton setFrame:CGRectMake(0, 0, 20, 20)];
self.navigationItem.titleView = titleButton;

This works great, except the resulting image in the navigation bar is only resized in the y-direction, resulting a smooshed appearance (unfortunately I can't post an image to show that because I don't have a reputation - you might be able to see it here: http://i.stack.imgur.com/fNh7O.png )

I can use a 20 x 20px image and it displays correctly, but that looks pixelated on the retina display.

So my main question is: what is the best way to add a button to the title area of a UINavigationBar? What is the best pixel size for an image for this button which will look sharp on both the older iphone screens, and the new retina displays? (clearly there is something about the pixel size of the images that I'm just not grasping - I thought that starting with a 40x40px or 60x60px image would be best).

Thanks for the help!

Why don't you try something like this :-------

UIButton *titleButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];

UIImage *settingsButtonImage = [UIImage imageNamed:@"settingsButton2X.png"];
[titleButton addTarget:self action:@selector(settingsButtonPress:) forControlEvents:UIControlEventTouchDown];
[titleButton setBackgroundImage:settingsButtonImage forState:UIControlStateNormal];
titleButton.center=self.navigationController.navigationBar.center;
titleButton.center=CGPointMake(titleButton.center.x, self.navigationController.navigationBar.frame.size.height/2);
[self.navigationController.navigationBar addSubview:titleButton];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM