gpt4 book ai didi

iphone - UINavigationBar 中的中心自定义标题?

转载 作者:行者123 更新时间:2023-12-03 18:21:11 25 4
gpt4 key购买 nike

我有一个自定义 UINavigationBar 标题和一个自定义后退按钮。我的问题是标题没有以 iPhone 为中心。就好像我的后退按钮将标题推到了右边。知道如何将其居中吗?

int height = self.navigationController.navigationBar.frame.size.height;
int width = self.navigationController.navigationBar.frame.size.width;


UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width + 300, 20)];
navLabel.backgroundColor = [UIColor whiteColor];
navLabel.textColor = [UIColor redColor];
navLabel.font = [UIFont fontWithName:@"Helvetica" size:30];
navLabel.textAlignment = UITextAlignmentCenter;
self.navigationItem.titleView = navLabel;
[navLabel release];
((UILabel *)self.navigationItem.titleView).text = self.title;

谢谢!

编辑我删除了多余的代码并添加了这张图片:

Picture of title off ceter

注意标题是如何被推到适应按钮的......

最佳答案

iOS 这样做是因为您初始化的帧始终是 300+ 宽度像素。它试图将整个框架居中,框架大于它想要容纳的空间(由于按钮),因此您的标签被推到右侧。您需要做的是为 navLabel 的 Frame 提供所需的最小尺寸。

因此,如果您的文本只有 100 像素宽,但框架为 400 像素,那么 iOS 会尝试将 400 像素置于导航标题的中心,但没有足够的空间。当您将大小设置为所需的实际 100 像素时,iOS 会将标题正确居中,因为有足够的空间来居中 100 像素。

下面的代码片段应该可以帮助您检测框架所需的最小尺寸,具体取决于您尝试输入的字体和文本。确保标签的边框尽可能小,但不超过最大宽度。(导航栏的宽度)。

UIFont* titleFont = [UIFont fontWithName:@"Helvetica" size:30];
CGSize requestedTitleSize = [titleText sizeWithAttributes:@{NSFontAttributeName: titleFont}];
CGFloat titleWidth = MIN(maxTitleWidth, requestedTitleSize.width);

UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleWidth, 20)];
navLabel.backgroundColor = [UIColor whiteColor];
navLabel.textColor = [UIColor redColor];
navLabel.font = [UIFont fontWithName:@"Helvetica" size:30];
navLabel.textAlignment = NSTextAlignmentCenter;
navLabel.text = titleText;
self.navigationItem.titleView = navLabel;

swift 5.0

    let titleFont = UIFont.systemFont(ofSize: 17.0)
let title = "My Title"
let titleSize = title.size(withAttributes: [.font: titleFont])

let frame = CGRect(x: 0, y: 0, width: titleSize.width, height: 20.0)
let titleLabel = UILabel(frame: frame)
titleLabel.font = titleFont
titleLabel.textColor = .red
titleLabel.textAlignment = .center
titleLabel.text = title
navigationItem.titleView = titleLabel

关于iphone - UINavigationBar 中的中心自定义标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9921026/

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