子视图的大小错误

时间:2017-03-27 22:15:03

标签: ios swift swift3

不幸的是我遇到了一个xib,我正在加载到scrollview中,并且它的行为并不像我期望的那样。

除非我设置了self.view.frame.size.height和self.view.frame.size.width,否则子视图的大小错误(太小)。

以下是似乎有用的值(水平模式):

iPhone SE: w:1136 h:608 navbar:32

iPhone 7: w:1334 h:718 navbar:32

iPhone 7 Plus: w:1366 h:784 navbar:44

iPad 9.7“: w:1366 h:980 navbar:44

我宁愿使用一种方法在运行时派生这些值,而不是对值进行硬编码。我尝试过使用UIScreen.main.bounds.width/heightUIScreen.main.nativeBounds.width/height,但是当nativeBound适用于某些人时,正常的似乎适用于其他人等。

主要ViewController代码

    let screenSize = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height
    let screenHeightWithoutBar = screenHeight - self.navigationController!.navigationBar.frame.height



    var TopicsArray = [String](arrayLiteral: "Topic1","Topic2","Topic3","Topic4","Topic5")
    var TopicItemArray = [TopicItemViewController]()

    for i in 0..<TopicsArray.count {

        let TopicItemVC :TopicItemViewController =  TopicItemViewController(nibName: "TopicItemViewController", bundle: nil);

        TopicItemVC.toPassTopicName = TopicsArray[i]

        self.addChildViewController(TopicItemVC);
        self.scrollView!.addSubview(TopicItemVC.view);
        TopicItemVC.didMove(toParentViewController: self);

        TopicItemArray.append(TopicItemVC)  
    }

    var topicCounter = 1
    for topicView in TopicItemArray {

        if(topicCounter<TopicItemArray.count){
            var topicFrame :CGRect = screenSize;

            topicFrame.origin.x = CGFloat(topicCounter) * screenWidth;

            TopicItemArray[topicCounter].view.frame = topicFrame;
        }

        topicCounter += 1
    }

    let scrollWidth: CGFloat  = CGFloat(TopicItemArray.count) * screenWidth
    let scrollHeight: CGFloat  = screenHeightWithoutBar

    self.scrollView!.contentSize = CGSize(width: scrollWidth, height: scrollHeight);

TopicItemViewController代码

    class TopicItemViewController: UIViewController {


     override func viewDidLoad() {
        super.viewDidLoad()
        var screenScale: CGFloat = UIScreen.main.scale
        //iphone 7 plus (nav is 44)
        self.view.frame.size.height = 784
        self.view.frame.size.width = 1366

        //iphone 7   // same as resolution   
        //nav is 32
        //self.view.frame.size.height = 718 //718+32 = 750
        //self.view.frame.size.width = 1334
     }
    }

1 个答案:

答案 0 :(得分:0)

所以经过大量的谷歌搜索和搞乱后,我已经解决了这个问题。

我确实可以摆脱硬编码,因为当我在viewDidLayoutSubviews而不是viewDidLoad中加载时,会选择正确的值!所有现有的约束开始按预期工作。在上面的示例中,我将删除self.view.frame.size.heightself.view.frame.size.width