我想在swift playgounds liveview中添加子视图以测试约束,但未能显示,添加的内部视图已消失。它只是在快看的时候画出来的,但是在liveview里面消失了,我怎么能用constaints修改内部视图的位置呢?

//: Playground - noun: a place where people can play

import UIKit
//import KeyBoardWubi
import PlaygroundSupport

var str = "Hello, playground"

var u1 : UIView

//u1 = KeyBoardWubi3(frame: CGRect(x: 20, y: 20, width: 200, height: 200))
//u1

var v1,v2,v3 : UIView

func addview(vin:UIView){
    var v4 : UIView
    v4 = UIView(frame : CGRect(x: 40, y: 40, width: 800, height: 100))
    v4.backgroundColor = UIColor.blue
    vin.addSubview(v4)
    v4.translatesAutoresizingMaskIntoConstraints = false
    v4.leftAnchor.constraint(equalTo: vin.leftAnchor, constant: 12.0).isActive = true
}

v1 = UIView(frame : CGRect(x: 0, y: 20, width: 200, height: 200))
v1.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = v1
addview(vin: v1)

v1

swift - 我想在swift parks liveview内添加subview进行测试约束,但无法显示,添加的内部 View 消失了-LMLPHP

最佳答案

自动布局约束无效。它只有左锚。Playground不会警告您无效的约束。如果这是一个真正的应用,你会知道的。
试试这个:

import UIKit
import PlaygroundSupport

func addview(vin:UIView){
    // Since you are using auto-layout, the initial frame is irrelevant
    let v4 = UIView(frame: .zero)
    v4.backgroundColor = .blue

    // Set this **before** adding v4 to another view
    v4.translatesAutoresizingMaskIntoConstraints = false

    vin.addSubview(v4)

    // Playground doesn't warn you about invalid auto layout constraints
    // This is where you set the size and position of the new view
    v4.leftAnchor.constraint(equalTo: vin.leftAnchor, constant: 40).isActive = true
    v4.topAnchor.constraint(equalTo: vin.topAnchor, constant: 40).isActive = true
    v4.widthAnchor.constraint(equalToConstant: 800).isActive = true
    v4.heightAnchor.constraint(equalToConstant: 100).isActive = true
}

let v1 = UIView(frame : CGRect(x: 0, y: 20, width: 200, height: 200))
v1.backgroundColor = UIColor.red
addview(vin: v1)
PlaygroundPage.current.liveView = v1

关于swift - 我想在swift parks liveview内添加subview进行测试约束,但无法显示,添加的内部 View 消失了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52903267/

10-11 06:35