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

标签 iphone uinavigationbar title

我有一个自定义 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/

相关文章:

iphone - 更改 UINavigationBar 的后退按钮

ios - iOS 中应用启动时是否存在应用间通信?

swift - 使用多个搜索栏和交互式弹出手势时导航项 View 消失

javascript - 如何在 Javascript 中获取 html 页面的标题

javascript - jquery 的 html5 视频上的 iOS "done"回调按钮

iphone - 应用程序在较低版本的 iPhone 中崩溃

ios - Xcode Interface Builder 模拟具有自定义高度的导航栏的指标

ios - 需要带 alpha 的导航栏但没有半透明模糊

javascript - 右键单击(上下文菜单)时有什么方法可以禁用工具提示(标题属性)?

iOS 导航栏标题动态设置在 View 出现时在文本中制作省略号