为什么我在添加UIView.xib时会有这个额外的空间?

时间:2018-04-17 14:43:35

标签: ios swift xib

为什么在将UIView.xib添加到用作UIViewController容器的UIView时,我有这个额外的空间。我正在使用Storyboard for UIViewController,xcode 9.2 ,.蓝色区域是containerView

Screen

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

        //Same problem if I am calling this into a Button action
        calendarView = ClassName(frame: containerView.frame)
        containerView.addSubview(calendarView)
    }   
}

class ClassName: UIView{
override init(frame: CGRect) {
    super.init(frame: frame)        
    commonInit()
}

 required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

private func commonInit(){        
    Bundle.main.loadNibNamed("NibName", owner: self, options: nil)
    addSubview(contentView)

    contentView.frame = bounds
    contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]


 }
}

1 个答案:

答案 0 :(得分:2)

“这是什么”这个问题的答案是:它是containerView和超级视图顶部之间的距离。

想一想。你有这一行:

calendarView = ClassName(frame: containerView.frame)

但下一行将是:

containerView.addSubview(calendarView)

但是你无法根据超级视图的框架来设置视图的框架。它们位于两个不同的坐标空间中!这里的结果是calendarView在其超级视图中偏移,正如containerView超级视图中偏移一样。通常结果会比这更糟糕。

你的意思是界限

calendarView = ClassName(frame: containerView.bounds)
containerView.addSubview(calendarView)

现在calendarView将完全填满containerView

(当然,您之后仍然会遇到问题,因为您没有使用自动布局定位事物。但至少这会为您提供您期望的初始位置。)