iOS,子视图大小无缘无故变化

时间:2017-08-30 08:29:03

标签: ios iphone swift

 @objc class SearchViewController: UIViewController {

     var uiView: UIView!

     @IBOutlet weak var reactWrapperView: UIView!

     override func viewDidLoad() {
         super.viewDidLoad()


         self.view.layer.borderColor = UIColor.yellow.cgColor
         self.view.layer.borderWidth = 2

         self.reactWrapperView.frame = (self.reactWrapperView.superview?.bounds)!
         self.reactWrapperView.layer.borderColor = UIColor.red.cgColor
         self.reactWrapperView.layer.borderWidth = 5

         self.uiView = UIView(frame: (self.reactWrapperView.superview?.bounds)!)
         self.uiView.layer.borderColor = UIColor.blue.cgColor
         self.uiView.layer.borderWidth = 10

         self.reactWrapperView.addSubview(self.uiView)

     }
 }

self.view和self.rectWrapperView在故事板中创建,它们与手机屏幕大小相同,如下图所示。

self.view : yellow
self.reactWrapperView : red
self.uiView: blue

如您所见,未显示底部蓝色边框,uiView似乎在增大。

我一直在苦苦挣扎很长时间,想知道什么会影响尺寸。

enter image description here

2 个答案:

答案 0 :(得分:0)

可能原因是:

     self.uiView = UIView(frame: (self.uiView.superview?.bounds)!)

你是否已经将uiview添加到someView?否则,为什么这个uiview有超级视图?

答案 1 :(得分:0)

您的Viewcontroller UI未更新(表示未完全加载),您可以移入主线程,还是将代码移至 viewwillappear viewDidAppear ,原因ui没有更新。

<强>选项1

override func viewDidLoad() {
         super.viewDidLoad()

         DispatchQueue.main.async { // or use sync


         self.view.layer.borderColor = UIColor.yellow.cgColor
         self.view.layer.borderWidth = 2

         self.reactWrapperView.frame = (self.reactWrapperView.superview?.bounds)!
         self.reactWrapperView.layer.borderColor = UIColor.red.cgColor
         self.reactWrapperView.layer.borderWidth = 5

         self.uiView = UIView(frame: (self.reactWrapperView.superview?.bounds)!)
         self.uiView.layer.borderColor = UIColor.blue.cgColor
         self.uiView.layer.borderWidth = 10

         self.reactWrapperView.addSubview(self.uiView)

     }
    }
 }

<强>选项2

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)


         self.view.layer.borderColor = UIColor.yellow.cgColor
         self.view.layer.borderWidth = 2

         self.reactWrapperView.frame = (self.reactWrapperView.superview?.bounds)!
         self.reactWrapperView.layer.borderColor = UIColor.red.cgColor
         self.reactWrapperView.layer.borderWidth = 5

         self.uiView = UIView(frame: (self.reactWrapperView.superview?.bounds)!)
         self.uiView.layer.borderColor = UIColor.blue.cgColor
         self.uiView.layer.borderWidth = 10

         self.reactWrapperView.addSubview(self.uiView)

     }
 }