ios - 以编程方式使用布局 anchor 创建 subview

标签 ios swift constraints layout-anchor

我已经使用 layout anchors 以编程方式创建了一个 UIView。现在我想在此 View 中添加一个 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 显示的。这是当前的 View 层次结构:

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()

这是在 Playground 中运行:

Showing the code running the a Playground

关于ios - 以编程方式使用布局 anchor 创建 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968233/

相关文章:

iOS AFNetworking post 请求返回 Request failed : bad request (400)

ios - 使用密码从URL提取数据

ios - 当我的应用程序未运行时如何处理 FCM?

macos - 在 Swift 中从下载的 NSData 创建 NSImage

iphone - 来自外部设备的意外输入 - iOS

iphone - 如何修复我的应用程序的 SIGABRT 错误?

ios - 通过使用其标记号来标识应更改的元素来更改 UITextView 文本

ios - Objective C 在代码中设置自动行高

Java @interface.List 组在自定义约束注释中不起作用

xcode - 向 SpriteNode 添加大小(约束)