如何在 Xcode 游乐场中使用自动布局约束显示视图?

2023-09-10移动开发问题
5

本文介绍了如何在 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)

提前致谢

推荐答案

也就是说你可以使用 PlaygroundPageliveView 属性来预览你的 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 游乐场中使用自动布局约束显示视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

[ios.cocos2d+box2d]如何禁用自动旋转?
[ios.cocos2d+box2d]how to disable auto-rotation?([ios.cocos2d+box2d]如何禁用自动旋转?)...
2024-08-12 移动开发问题
7

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9

如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?
How can I implement a virtual joystick for a cocos2d game outside the cocos2d environment?(如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?)...
2024-08-12 移动开发问题
13