swift - 我想在 swift playgounds 实时视图中添加子视图以测试约束但无法显示,添加的内部视图消失了
问题描述
我想在 swift playgounds 实时视图中添加子视图以测试约束但无法显示,添加的内部视图消失了。它只是在快速查看中绘制,但在实时视图中消失了,我如何使用约束修改内部视图的位置?
//: 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
解决方案
您的自动布局约束无效。它只有左锚。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
推荐阅读
- python - 每次按 Enter 时如何从用户那里获取数据并将这些数据传递给函数?
- shell - 为什么 zsh `for` 循环错误并带有 `command not found: filename.txt`?尽管 filename.txt 是参数而不是命令
- python - 如果存在第二列,则填充第二列值,否则在 Dataframe 中填充第一列值
- core - Google 创始选择对 CLS 的影响
- ios - 未调用 URLSessionDelegate 类 deinit
- docker - Docker:“无法拉取‘tomcat:8.5’:清单列表条目中没有与 linux/arm/v7 匹配的清单”
- python - 在特定时间以毫秒精度运行函数
- reactjs - React Context:开发人员工具中的 Sessionstorage 数据出现,但在导航栏中显示为空白
- ruby-on-rails - 当 webpack-dev-server 运行时,Rails 看不到 webpack 编译的文件
- r - ggplot2图的问题