UIViewController视图的框架在现有之后发生了变化(viewController:animated:completion :)

时间:2017-04-14 11:16:56

标签: ios iphone swift cocoa-touch uiviewcontroller

我有一个UIViewController我将其大小设置为ViewDidLoad,就像那样:

//Setting view's frame
let width = UIScreen.main.bounds.size.width - 10
let height = (43 * UIScreen.main.bounds.height) / 100 //%43 of the screen
self.view.frame = CGRect(x: 5, y: 80, width: width, height: height)

在我尝试提供另一个ViewController之前,它很有用:

//Presenting AutoCompleteVC
self.autocompleteVC = GMSAutocompleteViewController()
self.autocompleteVC.delegate = self
self.present(self.autocompleteVC, animated: true, completion: nil)

在我关闭此视图(self.autocompleteVC.dismiss(animated: true, completion: nil))后,第一个ViewController视图的框架会更改为全屏幕框架。

知道怎么解决吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

viewWillLayoutSubviews中设置框架。那时框架已经知道了。像这样:

public override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

   //Setting view's frame
   let width = UIScreen.main.bounds.size.width - 10
   let height = (43 * UIScreen.main.bounds.height) / 100 //%43 of the screen
   self.view.frame = CGRect(x: 5, y: 80, width: width, height: height)
}

答案 1 :(得分:1)

我建议您在viewWillAppear中编写代码,但在设置框架后,您应该编写@IBAction func mealsButtonAction(_ sender: UIButton) { if sender .isEqual(beforeMealsButton) { beforeMealsButton.isSelected = true beforeMealsButton .setImage(UIImage.init(named: "before_lunch_hover"), for: .normal) afterMealsButton .setImage(UIImage.init(named: "after_lunch_normal"), for: .normal) boolDict["bm"] = true boolDict["am"] = false } else { afterMealsButton.isSelected = true beforeMealsButton .setImage(UIImage.init(named: "before_lunch_normal"), for: .normal) afterMealsButton .setImage(UIImage.init(named: "after_lunch_hover"), for: .normal) boolDict["bm"] = false boolDict["am"] = true } }

我希望这会奏效。

答案 2 :(得分:0)

视图控制器的主视图由系统逻辑定位和调整大小,具体取决于横向/纵向,分屏,模态显示,视图控制器控制......

相反,您应该在子视图中进行每个内容布局(取决于主视图大小)并将主视图的背景颜色设置为UIColor.clear。 因此,在您的情况下,添加子视图并根据需要进行配置。

提示:您应该使用自动布局而不是操纵框架。