gpt4 book ai didi

ios - 更改 UINavigationBar 中 UIBarButtonItem 的宽度

转载 作者:IT王子 更新时间:2023-10-29 08:10:24 24 4
gpt4 key购买 nike

我正在创建一个 UIBarButtonItem 并将其添加到我的导航栏中,如下所示:

(void)viewDidLoad { 

...

// Add the refresh button to the navigation bar
UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
[refreshButton setFrame:CGRectMake(0,0,30,30)];
[refreshButton setImage:[UIImage imageNamed:@"G_refresh_icon.png"] forState:UIControlStateNormal];
[refreshButton addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *refreshBarButton = [[[UIBarButtonItem alloc] initWithCustomView:refreshButton] autorelease];
self.navigationItem.leftBarButtonItem = refreshBarButton;
}

运行时它看起来是正确的,但我可以通过在 x = 0 到大约 100 之间的任意位置点击导航栏来选择栏按钮项目。如何将可选区域的宽度调整为 30 像素?

最佳答案

从 iOS 11 开始,只为 customView 而不是 UIBarButtonItem 设置框架将不起作用(如 accepted answer 中的建议)。似乎将自动布局添加到 UIBarButtonItem 会覆盖设置的框架。 This post给了我一个想法:

navigationItem.leftBarButtonItem?.customView = yourCustomButtonView
let desiredWidth = 35.0
let desiredHeight = 35.0

let widthConstraint = NSLayoutConstraint(item: yourCustomButtonView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredWidth)
let heightConstraint = NSLayoutConstraint(item: yourCustomButtonView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredHeight)

yourCustomButtonView.addConstraints([widthConstraint, heightConstraint])

另请注意,您最好使用 UIButton 作为您的 CustomView,因为您必须依赖它来触发操作。

关于ios - 更改 UINavigationBar 中 UIBarButtonItem 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10988918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com