swift - Playground 中的 UIView

标签 swift uiview swift-playground

我定义了两个不同的 View ,比如-

第一种方法:

let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
containerView.backgroundColor = UIColor.redColor()

我可以看到矩形。

第二种方法:

let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
view.backgroundColor = UIColor.blueColor()

我看到一些日志消息,如输出。

为什么两者给出不同的输出?

网上有些教程使用第一种方法,有些使用第二种方法。

这是图片。

enter image description here

最佳答案

有时,playground 不会按预期工作。可能是因为两个 View 都没有定义父 View 。

在实际应用中它工作正常。

    override func viewDidLoad() {
    super.viewDidLoad()

    let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 37.5, height: 66.7))
    containerView.backgroundColor = UIColor.redColor()


    view.addSubview(containerView)       

    let myView = UIView()
    myView.frame = CGRect(x: 0, y: 290, width: 200, height: 200)
    myView.backgroundColor = UIColor.blueColor()

    view.addSubview(myView)
}

我在 playgorund 中试过这段代码:

let cv = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
cv.backgroundColor = UIColor.redColor()

let v1 = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 30.0, height: 60.0))
v1.backgroundColor = UIColor.yellowColor()

cv.addSubview(v1)

let v2 = UIView()
v2.frame = CGRect(x: 0, y: 200, width: 30.0, height: 60.0)
v2.backgroundColor = UIColor.blueColor()


cv.addSubview(v2)

它对两个初始化器都很好。

关于swift - Playground 中的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38820883/

相关文章:

arrays - 使用乘数步骤快速迭代数组

ios - iOS Swift 中的 UIView 填充动画?

ios - 无法将表达式的类型 'StaticString' 转换为类型 'StringLiteralConvertible' (Swift)

以函数作为参数的 Swift 函数

swift - 从 'NSPersistentStoreResult' 转换为无关类型 'Entity' 总是失败

swift - 在 imageView 中心添加标签

ios - JSONSerialization 选项有什么作用,它们如何改变 jsonResult?

ios - 如何更改 UIPageViewController 中页面指示器的背景颜色

ios - 对 UIView 的起源感到困惑

ios - UINavigationBar 不在 Playground 中显示项目部件