UINavigationBar title label text

前端 未结 3 1731
情歌与酒
情歌与酒 2021-01-12 19:40

Is it possible to get the title text to shrink to fit in the UINavigationBar in iOS.

(for portrait iPhone app with no autolayout).

I\'m setting

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 20:07

    I used this code for swift 4 (note label rect is NOT important..)

    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]
            }
        }
    

提交回复
热议问题