ios - 如何在 Xcode playground 中使用自动布局约束显示 View ?

标签 ios xcode swift autolayout swift-playground

我试图在 XCode playground 中显示配置了 autolayout 约束的 View ,但它似乎不起作用。就像 playground 完全忽略了约束,我在任何地方都找不到关于这个问题的信息。

这是我试过的代码:

let view = UIView()
view.frame = CGRectMake(0, 0, 400, 200)
view.backgroundColor = UIColor.lightGrayColor()

let label = UILabel() // I can only see the label if I set a frame
         // UILabel(frame: CGRectMake(0, 0, 200, 50))
label.backgroundColor = UIColor.greenColor()
label.text = "I am a label"
label.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label)

let views = ["label":label]
let options = NSLayoutFormatOptions(0)

let cs1 = NSLayoutConstraint.constraintsWithVisualFormat(
    "H:|-[label]-|", options: options, metrics: nil, views:views )

let cs2 = NSLayoutConstraint.constraintsWithVisualFormat(
    "V:|-[label]-|", options: options, metrics: nil, views:views )

view.addConstraints(cs1)
view.addConstraints(cs2)

提前致谢

最佳答案

也就是说,您可以使用 PlaygroundPageliveView 属性来预览您的 UI。

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView

这是一个 link进一步扩展了这一点。

如果它不起作用,你可能需要触发一个 layoutIfNeeded 但自 Swift 4 以来,这并不能真正解决问题

此外,在您的 View 中包含 translatesAutoresizingMaskIntoConstraints = false。喜欢:

import PlaygroundSupport

myLiveView.translatesAutoresizingMaskIntoConstraints = false
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView

关于ios - 如何在 Xcode playground 中使用自动布局约束显示 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333323/

相关文章:

iOS:rootController 中的方法不会被调用

ios - 如何更改 Xcode 中的工作区名称?

iPhone en_* 子语言本地化

ios - 隐藏后更改 UIButton 标题

ios - 在 Swift 中每次点击都执行一些操作

ios - CoreLocation 类的 Codable 扩展

SwiftUI 自定义重音颜色不适用于物理设备(iOS 13),但适用于其他任何地方(iOS 14.0+)

objective-c - 在 plist 文件中存储 Objective-C 代码

ios - 在 xcode 中使用 swift 使用 View 宽度无法正确调整后续 uilabel 的大小

ios - Core Data + iCloud Sync 确实改变了商店通知不刷新 UI