2015-03-02 63 views
1

我有一个UIView,我正在绘制并将子视图添加到另一个UIView。UIView的宽度不会根据约束进行更改

这充当分隔符,因此它需要高1px并且视图的宽度被添加。

这是我到目前为止的代码:

var underline = UIView() 
underline.frame = CGRectMake(0, 37, backgroundSection.bounds.size.width, 1) 
underline.backgroundColor = UIColor.whiteColor() 
backgroundSection.addSubview(underline) 

这并不绘制的UIView的宽度是相同的宽度backgroundSection。这会将其绘制为与约束重新调整视图前backgroundSection在IB上的宽度相同。

我可以将backgroundSection的clipToBounds设置为true,但是如果将backgroundSection设置为true,则会在backgroundSection上移除它。

我该如何解决这个问题。

谢谢, 亚历克斯

回答

1

当您正在使用的限制,否则不应使用框架的设置来。自动布局将为您完成所有框架设置。

相反,你需要将约束添加到您的视图:

var underline = UIView() 
backgroundSection.addSubview(underline) 

// These two lines will add horizontal and vertical constraints pinning the underline view to backgroundSection's edges 
backgroundSection.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: nil, metrics: nil, views: ["view": underline])) 
backgroundSection.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: nil, metrics: nil, views: ["view": underline]))