在UIStackView中设置anchorPoint和位置

时间:2017-10-28 23:27:06

标签: ios swift uikit core-animation

我通过Interface Builder将UIView添加到UIStackView(出于演示的目的)。我需要将此子视图转换为其原点,因此我将layer.anchorPointlayer.position设置为CGPoint(0, 0)。当视图出现时,图层会移动到新的anchorPoint,但是在CGPoint(0.5, 0.5).的原始位置,好像我没有设置{{1}完全没有。

相比之下,我尝试在没有堆栈视图的情况下将相同的子视图添加到另一个layer.position,并按预期重新调整。以下是设置子视图UIViewanchorPoint的结果:

layer.position

enter image description here

现在,当我在将子视图添加到堆栈视图之前设置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) anchorPoint时,只会尊重position

anchorPoint

enter image description here

我希望这看起来与第一张图片相同。

是否存在覆盖子视图层// 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约束? IRL我使用自动布局的界面生成器(我不会认为因为iOS 8以来自动布局已经变换,因此无关紧要),并重置position position中的viewDidLayoutSubviews()仍然不可靠,因为在frame被调用之前,子视图的positionviewDidAppear都是正确的,此时subview是固执的重新定位为stackView认为合适。

如何在anchorPoint中设置视图layer.positionUIStackView

1 个答案:

答案 0 :(得分:0)

anchorPoint正常工作,因为默认为中心(0.5,0.5), set(0,0)表示相对于位置偏移一半。

如果你想改变内部视图的位置,因为UIStack会根据设计自动调整位置填充,所以位置的改变对视图没有影响
或者,你可以通过使用变换来改变位置:

subview.transform = CGAffineTransform(translationX: 100, y: 100)  

或添加到退出变换(默认为无变换矩阵)

subview.transform = subview.transform.translatedBy(x: 100, y: 100)

上面的代码意味着它改变位置(100,100)

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

subview.transform = subview.transform.rotated(by: 50)

或放大它:

subview.transform = subview.transform.scaledBy(x: 1.5, y: 1.2)
相关问题