在使用不同的帧和图像值返回VC时,UIBarButtonItem调整大小时出现问题。
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
}
第一次完美尺寸为selectedR = 1
返回viewDidLoad并使用不同的selectedR值和图像爆炸,扭曲和设置leftFrame大小不受尊重。
这一切在swift 3中都很完美,但很快它就到处都是。任何帮助或建议将不胜感激。
答案 0 :(得分:2)
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
}
Apple的2017年WWDC会议Updating Your App for iOS 11涵盖了这一点。