Swift之導覽列標題文字太長,導致返回按鈕文字消失問題解決

來源:互聯網
上載者:User

項目中常常會使用 UINavigationController 對各個頁面進行導航,導覽列左側的返回按鈕預設標題文字是上級頁面的 title。


但如果子頁面的標題(title)文字過長,那麼返回按鈕的文字就會消失:
 
同樣地,即使在父頁面中將 navigationItem.backBarButtonItem 設為自訂的 UIBarButtonItem,修改返回按鈕的文字:
 

如果子頁面的標題文字過長,返回按鈕的文字也是就會消失:

 
解決辦法:將導覽列標題視圖替換成自訂label,並限制長度尺寸

通過 navigationItem.titleView 屬性可以很方便的將其替換成自訂的 UIView 視圖,這裡我們使用固定尺寸的 UILabel,效果圖如下:

import UIKit
 
class DetailViewController: UIViewController {
     
    override func viewDidLoad() {
        let titleView = UIView(frame: CGRectMake(0, 0, 200, 40))
        let labelForTitle = UILabel(frame: CGRectMake(0, 0, 200, 30))
        labelForTitle.font = UIFont.systemFontOfSize(17.0, weight: UIFontWeightMedium)
        labelForTitle.center = titleView.center
        labelForTitle.text = "文章列表(歡迎訪問hangge.com)"
        titleView.addSubview(labelForTitle)
        self.navigationItem.titleView = titleView
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
功能改進:如果文字過長,label自動縮小文字大小
上面的方法會把多餘的文字截斷並在後面添加...。如果想讓標題文字能完全顯示,可以通過 adjustsFontSizeToFitWidth 屬性讓文字標籤自動縮放文字尺寸以適應標籤大小。效果圖如下:

import UIKit
 
class DetailViewController: UIViewController {
     
    override func viewDidLoad() {
        let titleView = UIView(frame: CGRectMake(0, 0, 200, 40))
        let labelForTitle = UILabel(frame: CGRectMake(0, 0, 200, 30))
        labelForTitle.font = UIFont.systemFontOfSize(17.0, weight: UIFontWeightMedium)
        labelForTitle.center = titleView.center
        labelForTitle.adjustsFontSizeToFitWidth = true
        labelForTitle.text = "文章列表(歡迎訪問hangge.com)"
        titleView.addSubview(labelForTitle)
        self.navigationItem.titleView = titleView
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.