必须有一种更好的方法来用UIScrollView
,UILabel
和其他内容填充UIImageView
,而不必用开始位置定义CGRectMake
。是否有堆叠视图之类的东西?我不是真的,但是动态添加内容的正确方法是什么。
[这里我正在做的事情:
func configureView() {
self.addHeaderImage()
var scrollView: UIScrollView!
var missionStatement: UILabel!
var missionStatementText: UILabel!
var history: UILabel!
var historyText: UILabel!
scrollView = UIScrollView()
scrollView!.frame = CGRectMake(0, headerImage.bounds.height, self.view.bounds.width, self.view.bounds.height)
scrollView!.contentSize = CGSize(width: self.view.bounds.width, height: self.view.bounds.height * 2)
scrollView!.autoresizingMask = UIViewAutoresizing.FlexibleHeight
self.view.addSubview(scrollView)
missionStatement = UILabel()
missionStatement!.frame = CGRectMake(10, 5, headerImage.bounds.width - 20, 30)
missionStatement!.text = "Our Mission Statement"
missionStatement!.font = UIFont(name: "HelveticaNeue-Bold", size: 22.0)
scrollView.addSubview(missionStatement)
missionStatementText = UILabel()
missionStatementText!.frame = CGRectMake(10, missionStatement.frame.height, headerImage.bounds.width - 20, 100)
missionStatementText!.text = "Covenant United Methodist Church, as a companionate community, serves people through the sharing, caring, and reaching out in the name of Jesus Christ."
missionStatementText!.font = UIFont(name: "HelveticaNeue", size: 17.0)
missionStatementText!.numberOfLines = 0
scrollView.addSubview(missionStatementText)
history = UILabel()
// By the time Im done adding things to this 1 view, Its going to be an insane addition problem to find the starting y of the rectangle
history!.frame = CGRectMake(0, missionStatement.frame.height, 0, 0)
}
您可以编写UIView的扩展名
extension UIView {
func addSubviewAtBottomOfAllSubviews(view:UIView){
var maxY = CGFloat(0)
for subview in self.subviews{
if maxY < subview.frame.maxY{
maxY = subview.frame.maxY
}
}
view.frame.origin.y = maxY
self.addSubview(view)
}
}
并且还要编写func来调整Scroll内容视图的大小,因此,如果视图的高度大于滚动视图的大小,则使其可滚动。>
extension UIScrollView{ func resizeContentSize(){ var contentRect = CGRectZero; for view in self.subviews{ contentRect = CGRectUnion(contentRect, (view ).frame); } self.contentSize = contentRect.size; } }
用途:
scrollView.addSubviewAtBottomOfAllSubviews(textLabel)
scrollView.addSubviewAtBottomOfAllSubviews(anotherView)
scrollView.resizeContentSize()
@ Daniel Krom的改进和扩展答案: