ios 在代码中调整 UIBarButtonItem 的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6950325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:58:17  来源:igfitidea点击:

Resize UIBarButtonItem in code

ioscocoa-touchuibarbuttonitem

提问by Hyman Humphries

How do I resize a UIBarButtonItem in the code?

如何在代码中调整 UIBarButtonItem 的大小?

回答by fsaint

You can't resize a UIBarButtonItem as you would a UIView. What you can do is change its widthproperty.

您不能像调整 UIView 那样调整 UIBarButtonItem 的大小。你可以做的是改变它的宽度属性。

UIBarButtonItem *b;
// Initialize and such ...
b.width = 150.0;

This should work for a Fixed Space Bar Button Item.

这应该适用于固定空格键按钮项目。

回答by Onur Var

If you want to use some custom image in UIBarButtonItem, you can use this code.

如果你想在 UIBarButtonItem 中使用一些自定义图像,你可以使用这个代码。

DoneButton = [[UIBarButtonItem alloc] initWithTitle:[Settings getConfigurableLabel:GENERAL_DONE] style:UIBarButtonItemStyleBordered target:self action:@selector(btnWorkOrderDoneClicked)];
UIButton *cameraButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)];
UIImage *cameraImage = [UIImage imageNamed:@"cameraicon_white.png"];
[cameraButton setBackgroundImage:cameraImage forState:UIControlStateNormal];
[cameraButton addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* cameraButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cameraButton];

回答by Carl

Use the UIBarButtonItem's width property to resize the button to fit by setting it to 0.

使用 UIBarButtonItem 的 width 属性通过将其设置为 0 来调整按钮的大小以适应。

UIBarButtonItem* btn = // init
btn.width = .0f;

From Apple's docs: "If the value is 0.0 or negative, the item sets the width of the combined image and title to fit" https://developer.apple.com/library/ios/documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html#//apple_ref/occ/instp/UIBarButtonItem/width

来自 Apple 的文档:“如果值为 0.0 或负数,则该项目将组合图像和标题的宽度设置为适合” https://developer.apple.com/library/ios/documentation/uikit/reference/UIBarButtonItem_Class/Reference /Reference.html#//apple_ref/occ/instp/UIBarButtonItem/width