如何在Swift中通过编程方式移动UIView

17
问题是如何在Swift中编程地移动“InfoView”(UIView)。
在Storyboard中存在以下约束条件(参见图像):
现在,我想将“InfoView”在“MyView”中向上或向下移动。
我尝试过:
@IBOutlet weak var infoTextLabel: UILabel!
@IBOutlet weak var infoTextLabelView: UIView!

// set infoTextLabel color
self.infoTextLabel.textColor = UIColor.blackColor()
// set infoTextLabel text
self.infoTextLabel.text = "hello"
// unhide infoTextLabel
self.infoTextLabel.hidden = false

// For the moving in Y-direction, I tried this - but does not work !!!!!!!
self.infoTextLabelView.frame.origin.y += 200

自动布局约束是否起作用?如何通过编程方式克服这些问题。或者 frame.origin.y 方法是错误的吗?

非常感谢您的任何帮助!


你是想创建一个动画还是只是想移动视图的位置而不需要动画序列? - Jeffrey
不需要动画! - iKK
4个回答

25

使用约束时,不要直接设置视图的框架。相反,重新配置约束并让自动布局引擎为您设置视图的框架。在您的视图控制器中创建一个IBOutlet以存储对“Center Y Alignment constraint”约束的引用。确保在故事板或xib中连接它。

@IBOutlet var yConstraint: NSLayoutConstraint

然后,您可以将约束条件的常量属性设置为从Y位置偏移(正数会向下移动,负数会向上移动)。

yConstraint.constant = 200

这将向下移动您的视图200点。


太好了!非常感谢! - Daniele B

17

参见我回答的另一个问题,其中介绍了一种使用自动布局程序移动视图的好方法: https://stackoverflow.com/a/30687856/3149796

此外,根据您想要的效果和UI的其他要求,您也可以使用变换来实现此目的,而不会干扰自动布局。

// Create a new transform
self.infoTextLabelView.transform = CGAffineTransformMakeTranslation( 0.0, 200.0 )

// Or modify existing transform
self.infoTextLabelView.transform = CGAffineTransformTranslate( self.infoTextLabelView.transform, 0.0, 200.0  )

请确保关闭AutoResizing约束,否则第二个选项将无法正常工作。 - Dan M
我不确定你的意思,dan m。直到今天,这两个例子似乎都按预期工作。你能更具体一些吗? - Patrick Lynch

9

Swift 4

UIView.animateKeyframes(withDuration: 0.25, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: 7), animations: {
       self.infoTextLabelView.frame.origin.y+=200

},completion: nil)

什么是rawValue: 7的含义? - Yaroslav Dukal
Swift 5 - UIView.animateKeyframes(withDuration: 0.25, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: 7), animations: { self.infoTextLabelView.frame.origin.y+=200 },completion: nil) - Roney Sampaio
甚至像这样简单的东西?:UIView.animate(withDuration: 0.1) { self.formSV.frame.origin.y += 100 } - Marcos
这对我来说是可行的,结果相同:UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, animations: { self.infoTextLabelView.frame.origin.y+=200 },completion: nil) - 7RedBits.com

8

Swift 5

使用CGAffineTransform

@IBOutlet weak var mainCurtain: UIView!

func moveUp() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options:[], animations: {
        self.mainCurtain.transform = CGAffineTransform(translationX: 0, y: 0)
    }, completion: nil)
}


func moveDown() {
    UIView.animate(withDuration: 0.5, delay: 0.0, options:[], animations: {
        let screenSize = UIScreen.main.bounds.size
        self.mainCurtain.transform = CGAffineTransform(translationX: 0, y: screenSize.height * 0.5)
    }, completion: nil)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接