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

How to move a UIView programmatically in Swift

问题是在 Swift 中以编程方式移动 "InfoView" (UIView)。

情节提要中存在以下约束(见图):

现在,我想将 "MyView" 中的 "InfoView" 向上或向下移动。

我试过了:

@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 方法错了 ??

感谢对此的任何帮助!

请参阅我对另一个问题的回答,了解使用自动布局以编程方式移动视图的好方法:

此外,根据您想要的效果和您的 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  )

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

@IBOutlet var yConstraint: NSLayoutConstraint

然后你可以设置约束的常量属性使其偏离Y位置(正数将向下移动,负数将向上移动)。

yConstraint.constant = 200

这会将您的观点向下移动 200 点。

Swift 4

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

},completion: nil)

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)
}