How can I display views using autolayout constraints in Xcode playground?(如何在 Xcode 游乐场中使用自动布局约束显示视图?)
问题描述
我试图在 XCode playground 中显示配置有 autolayout 约束的视图,但它似乎不起作用.就像游乐场完全忽略了约束,我在任何地方都找不到有关此问题的信息.
I am trying to display views configured with autolayout constraints in XCode playground, but it doesn't seem to work. It's like playground ignores the constraints completely, and I can't find information about this issue anywhere.
这是我尝试过的代码:
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)
提前致谢
推荐答案
也就是说你可以使用 PlaygroundPage
的 liveView
属性来预览你的 UI.
That being said you can use the liveView
property of PlaygroundPage
to preview your UI.
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView
这是一个进一步扩展的 链接.
Here's a link that expands on this further.
如果它不起作用,您可能需要触发 layoutIfNeeded
但这不应该真正解决问题,因为 Swift 4
If its not working you may need to trigger a layoutIfNeeded
but that shouldn't really solve the issue since Swift 4
另外,在您的视图中包含 translatesAutoresizingMaskIntoConstraints = false
.喜欢:
Also, include translatesAutoresizingMaskIntoConstraints = false
on your view. Like:
import PlaygroundSupport
myLiveView.translatesAutoresizingMaskIntoConstraints = false
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView
这篇关于如何在 Xcode 游乐场中使用自动布局约束显示视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Xcode 游乐场中使用自动布局约束显示视图?
基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01