Swift Playground Live View Size

It's hard for me to figure out how to lay out views in Swift Playgrounds for iPad, although this may also be relevant to Mac users.

The following code should create a view with a red square (also a view) that is near the edges of its superview, but does not touch them.

let v = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) let sqv = UIView(frame: CGRect(x: 400, y: 400, width: 50, height: 50)) sqv.backgroundColor = .red v.addSubview(sqv) PlaygroundPage.current.liveView = v 

The result is not what you expect:

enter image description here

I suspect that I know what is happening here; live views have a fixed size that is larger than the display area. Some characteristics of the view are ignored when they act as live view. However, I cannot find where this is mentioned in the documentation, which annoys me. More importantly, how do I handle this? I would like to be able to build simple user interfaces that change according to the current size of the live view. I don’t know how to solve this problem without trial and error and hard coding, and these are two things that I would really like to avoid.

+5
source share
2 answers

I suspect that I know what is happening here; live views have a fixed size that is larger than the display area.

Actually, it looks more like a different path. The iPad screen has a width of 1024 pixels (in landscape orientation). The right pane (where it shows your live view) is 512 pixels wide. The playground makes your root view ( v ) fill this panel, insert 40 dots on the left, right and top (and more below). Thus, the width of your root directory will be 432 (= 512 - 2 * 40), which is less than the 500 you specify.

The views created in the code (for example, yours) have translatesAutoresizingMaskIntoConstraints = true and a mask for resizing 0, which means that when resizing the parent element, it does not adjust the frame of the view. Thus, the playground resizes your root view to a width of 432, but your root view does not move or resize its subset ( sqv ).

The simplest fix is ​​to set the preview auto-mask to express your intention that it will stay near the right and bottom edges of the root view. This means that it must have flexible top and left margins:

 let v = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) let sqv = UIView(frame: CGRect(x: 400, y: 400, width: 50, height: 50)) sqv.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin] sqv.backgroundColor = .red v.addSubview(sqv) PlaygroundPage.current.liveView = v 

Result:

enter image description here

+6
source
 let sqv = UIView(frame: CGRect(x: UIScreen.mainScreen().bounds.width-50-1, y:400, width: 50, height: 50)) 

The code above puts your spy object 1 point to the right of the main view. Try changing the value 1 after 50 in x to the desired value.

0
source

All Articles