首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置anchorPoint和UIStackView中的位置

设置anchorPoint和UIStackView中的位置
EN

Stack Overflow用户
提问于 2017-10-28 23:27:06
回答 1查看 935关注 0票数 0

我通过Interface将一个UIView添加到UIStackView中(为了演示起见)。我需要转换这个子视图的原点,所以我将layer.anchorPointlayer.position设置为CGPoint(0, 0)。当视图出现时,该层被移动到它的新anchorPoint上,但在它原来的CGPoint(0.5, 0.5).位置上,就好像我根本没有设置layer.position

相反,我尝试在没有堆栈视图的情况下将相同的子视图添加到另一个UIView中,并按预期进行了调整。以下是不设置子视图的anchorPointlayer.position的结果

代码语言:javascript
复制
let background = UIView(frame: CGRect(x: 0, y: 0, width: 265, height: 55))
background.backgroundColor = UIColor.blue
PlaygroundPage.current.liveView = background

let stackView = UIStackView(frame: background.bounds)
background.addSubview(stackView)

let subview = UIView()
subview.backgroundColor = .red
stackView.addArrangedSubview(subview)

现在,当我在将子视图添加到堆栈视图之前设置anchorPointposition时,只尊重anchorPoint

代码语言:javascript
复制
// same
let background = UIView(frame: CGRect(x: 0, y: 0, width: 265, height: 55))
background.backgroundColor = UIColor.blue
PlaygroundPage.current.liveView = background

// same
let stackView = UIStackView(frame: background.bounds)
background.addSubview(stackView)

let subview = UIView()
subview.backgroundColor = .red
subview.layer.anchorPoint = CGPoint(x: 0, y: 0) // added
subview.layer.position = CGPoint(x: 0, y: 0) // added
stackView.addArrangedSubview(subview)

print(subview.layer.position) // (132.5, 27.5)

我希望这张照片和第一张一样。

是否有隐含的UIStackView约束覆盖子视图层的position?IRL我使用的是带有自动布局的接口生成器(我认为这并不重要,因为从iOS 8开始自动布局是对转换友好的),而在viewDidLayoutSubviews()中重置position仍然不可靠,因为子视图的frameposition都是正确的,直到viewDidAppear被调用,此时subview会在stackView认为合适的情况下被顽固地重新定位。

如何在anchorPoint UIStackView**?**中设置视图的

EN

回答 1

Stack Overflow用户

发布于 2017-10-29 01:12:33

由于缺省值为中心(0.5,0.5),set (0,0)相对于位置的平均值移动了一半,所以anchorPoint是按其工作方式工作的。

如果您想要更改内部视图的位置,因为UIStack将按其设计的方式自动调整该位置,因此更改位置对视图没有任何影响。

或者,您可以通过使用转换来更改位置:

代码语言:javascript
复制
subview.transform = CGAffineTransform(translationX: 100, y: 100)  

或添加到退出转换中(默认值为无转换矩阵)

代码语言:javascript
复制
subview.transform = subview.transform.translatedBy(x: 100, y: 100)

以上代码表示它移动了位置(100,100)

你也可以把它旋转(比如向左转50度)。

代码语言:javascript
复制
subview.transform = subview.transform.rotated(by: 50)

或者扩大它:

代码语言:javascript
复制
subview.transform = subview.transform.scaledBy(x: 1.5, y: 1.2)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46995489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档