我正在以编程方式向容器视图添加UIView(但是容器视图是在storyboard中创建的)。这是代码:
class ViewController: UIViewController{
@IBOutlet weak var dwView: UIView!
private var dwSelector = dwSelectorView()
override func viewDidLoad(){
super.viewDidLoad()
addDWSelector()
}
func addDWSelector(){
dwSelector.setTranslatesAutoresizingMaskIntoConstraints(false)
dwSelector.frame = CGRectMake(self.dwView.bounds.origin.x, self.dwView.bounds.origin.y, self.dwView.bounds.width / 2.0, self.dwView.frame.height)
println("dw height: \(self.dwView.frame.height)")
//prints 568, way too large of a value
self.dwView.addSubview(dwSelector)
}
}
故事板中dwView
的高度为123
,但打印状态为568
,所以现在看起来就是这样:
答案 0 :(得分:3)
您应始终不依赖-(void)viewDidLoad
,因为此时视图边界不正确,或- (void)viewWillAppear
如果您使用自动布局设置视图的框架。如果在UIViewController中布局视图,viewDidLayoutSubviews()
是一个合适的位置,如果在UIView中布局子视图,它是layoutSubviews()
。
查看此文章以获取更多详细信息:Where to progmatically lay out views in iOS 5 (and handling orientation changes)
答案 1 :(得分:0)
你试过在viewWillAppear()中调用addDWSelector()吗?