2017-09-13 48 views
0

在使用不同的幀和圖像值返回到VC時調整UIBarButtonItem大小時遇到​​問題。對於selectedR = 1在Swift4中,替換navigationItem.leftBarButtonItem調整大小無用

編輯回viewDidLoad中具有不同的值selectedR和圖像

var selectedR = 1 
var leftFrame = CGRect() 
var leftImage = UIImage() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    if selectedR == 0 
    { 
     leftFrame = CGRect(x: 0, y: 0, width: 33, height: 33) 
     leftImage = UIImage(named: 「pic-0」)! 
    } 
    else if selectedR == 1 
    { 
     leftFrame = CGRect(x: 0, y: 0, width: 79, height: 33) 
     leftImage = UIImage(named: "pic-1")! 
    } 
    else if selectedR == 2 
    { 
     leftFrame = CGRect(x: 0, y: 0, width: 34, height: 33) 
     leftImage = UIImage(named: "pic-2」)! 
    } 

    let cButton = UIButton(frame: leftFrame) 
    cButton.setImage(leftImage, for: UIControlState()) 
    cButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside) 
    cButton.contentMode = UIViewContentMode.scaleAspectFit 
    let leftItem = UIBarButtonItem(customView: cButton) 
    self.navigationItem.leftBarButtonItem = leftItem 
} 

第一次完美的大小炸燬,扭曲和設置leftFrame尺寸不兌現。

這一切都在迅速3完美,但迅速4它遍佈各地。任何幫助或建議將不勝感激。

+0

爲什麼viewDidLoad被多次調用? – beyowulf

+0

從我所知道的是我使用的框架(SWRevealViewController)是如何工作的。並且在Swift 3中工作得很完美。這就是說,很可能確實是這個問題。你怎麼看? –

+1

我只是想確保你沒有手動調用系統應該處理的'viewDidLoad'。我的猜測是iOS 10和11之間的一個主要變化是現在欄按鈕項由自動佈局引擎佈置。然而,這種變化應該是向後兼容的。你可以試試'cButton.widthAnchor.constraint(equalToConstant:leftFrame.width).isActive = true; cButton.heightAnchor.constraint(equalToConstant:leftFrame.height).isActive = true'你可以在這裏看到更多關於它的信息https://developer.apple.com/videos/play/wwdc2017/204/ – beyowulf

回答

1

iOS 10和11之間的一個主要變化是現在欄按鈕項由自動佈局引擎佈置。通常應該向後兼容。但是,如果您在佈置條形按鈕項目時遇到問題,則應嘗試設置約束條件並查看是否可以解決您的問題。

在你的情況下,你會說:

var selectedR = 1 
var leftFrame = CGRect() 
var leftImage = UIImage() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    if selectedR == 0 
    { 
     leftFrame = CGRect(x: 0, y: 0, width: 33, height: 33) 
     leftImage = UIImage(named: 「pic-0」)! 
    } 
    else if selectedR == 1 
    { 
     leftFrame = CGRect(x: 0, y: 0, width: 79, height: 33) 
     leftImage = UIImage(named: "pic-1")! 
    } 
    else if selectedR == 2 
    { 
     leftFrame = CGRect(x: 0, y: 0, width: 34, height: 33) 
     leftImage = UIImage(named: "pic-2」)! 
    } 

    let cButton = UIButton(frame: leftFrame) 
    cButton.widthAnchor.constraint(equalToConstant: leftFrame.width).isActive = true 
    cButton.heightAnchor.constraint(equalToConstant: leftFrame.height).isActive = true 
    cButton.setImage(leftImage, for: UIControlState()) 
    cButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside) 
    cButton.contentMode = UIViewContentMode.scaleAspectFit 
    let leftItem = UIBarButtonItem(customView: cButton) 
    self.navigationItem.leftBarButtonItem = leftItem 
} 

這是覆蓋在蘋果的WWDC 2017年會議Updating Your App for iOS 11