UINavigationBar标题标签文本

时间:2013-01-24 15:50:56

标签: iphone ios objective-c uinavigationbar

是否可以缩小标题文字以适应iOS中的UINavigationBar

(对于没有自动布局的人像iPhone应用程序)。

我正在动态设置标题栏,但有时文字太长,目前它只是用省略号将其剪掉。

即。 “这就是......”

我希望它缩小文字。

3 个答案:

答案 0 :(得分:9)

您可以创建自己的标题视图来制作它。

这样的事情:

- (void)viewDidLoad
{
    [super viewDidLoad];

  //Do any additional setup after loading the view, typically from a nib.
     UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; //<<---- Actually will be auto-resized according to frame of navigation bar;
    [titleLabelView setBackgroundColor:[UIColor clearColor]];
    [titleLabelView setTextAlignment: NSTextAlignmentCenter];
    [titleLabelView setTextColor:[UIColor whiteColor]];
    [titleLabelView setFont:[UIFont systemFontOfSize: 27]]; //<<--- Greatest font size
    [titleLabelView setAdjustsFontSizeToFitWidth:YES]; //<<---- Allow shrink
     // [titleLabelView setAdjustsLetterSpacingToFitWidth:YES];  //<<-- Another option for iOS 6+
    titleLabelView.text = @"This is a Title";

    navigationBar.topItem.titleView = titleLabelView;

    //....
}

希望这有帮助。

答案 1 :(得分:2)

Xcode 7.1 - Swift 2.0


//Adding Title Label
        var navigationTitlelabel = UILabel(frame: CGRectMake(0, 0, 200, 21))
        navigationTitlelabel.center = CGPointMake(160, 284)
        navigationTitlelabel.textAlignment = NSTextAlignment.Center
        navigationTitlelabel.textColor  = UIColor.whiteColor()
        navigationTitlelabel.text = "WORK ORDER"
        self.navigationController!.navigationBar.topItem!.titleView = navigationTitlelabel

答案 2 :(得分:0)

我将此代码用于swift 4(注意标签rect并不重要..)

func navBar()->UINavigationBar?{
        let navBar = self.navigationController?.navigationBar
        return navBar
    }


override func viewDidLoad() {
        super.viewDidLoad()

        setTNavBarTitleAsLabel(title: "VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY LONGGGGGG")
    }

    // will shrink label...

    func setTNavBarTitleAsLabel(title: String, color: UIColor ){

        // removed some code..

        let navigationTitlelabel = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        navigationTitlelabel.numberOfLines = 1
        navigationTitlelabel.lineBreakMode = .byTruncatingTail

        navigationTitlelabel.adjustsFontSizeToFitWidth = true
        navigationTitlelabel.minimumScaleFactor = 0.1
        navigationTitlelabel.textAlignment = .center
        navigationTitlelabel.textColor  = color
        navigationTitlelabel.text = title

        if let navBar = navBar(){
            //was navBar.topItem?.title = title

            self.navBar()?.topItem?.titleView = navigationTitlelabel
            //navBar.titleTextAttributes = [.foregroundColor : color ?? .black]
        }
    }