我已经使用布局锚点以编程方式创建了一个UIView.现在我想在这个视图中添加一个UILabel.到目前为止,这是我的代码:
let centerView = UIView() centerView.translatesAutoresizingMaskIntoConstraints = false centerView.backgroundColor = UIColor.white view.addSubview(centerView) centerView.leftAnchor.constraint(equalTo: view.leftAnchor,constraint: 20).isActive = true centerView.rightAnchor.constraint(equalTo: view.rightAnchor,constraint: -20).isActive = true let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Testing" label.textColor = UIColor.black centerView.addSubview(label) label.leftAnchor.constraint(equalTo: centerView.leftAnchor).isActive = true
我认为这个标签会在参考centerView时显示,但它是在参考UIWindow时显示的.这是当前的视图层次结构:
UIWindow --> UIView (centerView) --> UILabel (label)
我需要在centerView中添加多个标签,根据我的理解,这个链会变长,而我想要几个标签都在centerView下面
UIWindow | UIView (centerView) / | \ Label 1 Label 2 Label 3
我怎样才能实现这种层次结构?
解决方法
你正确地做了,你没有提供足够的约束.我在Swift Playground中尝试了您的代码并添加了一些额外的约束,它显示标签相对于centerView按预期放置:
let view = UIView(frame: CGRect(x: 0,y: 0,width: 300,height: 500)) let centerView = UIView() centerView.translatesAutoresizingMaskIntoConstraints = false centerView.backgroundColor = UIColor.white view.addSubview(centerView) centerView.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 20).isActive = true centerView.rightAnchor.constraint(equalTo: view.rightAnchor,constant: -20).isActive = true centerView.topAnchor.constraint(equalTo: view.topAnchor,constant: 20).isActive = true centerView.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: -20).isActive = true let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Testing" label.textColor = UIColor.black label.backgroundColor = UIColor.yellow centerView.addSubview(label) label.leftAnchor.constraint(equalTo: centerView.leftAnchor).isActive = true label.topAnchor.constraint(equalTo: centerView.topAnchor).isActive = true view.layoutIfNeeded()
这是在游乐场运行:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。