如何在Swift中从左向右移动图像视图

时间:2016-01-31 13:53:02

标签: ios swift

我试图制作一个自定义切换按钮,其中的图像视图在单击时移动到其容器的右侧,再次单击时移动到容器的左侧。我需要什么代码?

import Foundation
import UIKit

internal class container : UIViewController {

@IBOutlet weak var shape: UIImageView!


override internal func viewDidLoad() {
    self.view.layer.cornerRadius = 10;
}



@IBAction func shapeMove(sender: AnyObject) {

}
}

shape是应该从左向右移动的图像视图。

1 个答案:

答案 0 :(得分:0)

维护bool变量以维持状态。

var isImageLeftSide = true

@IBAction func shapeMove(sender: AnyObject) {
    var customFrame = shape.frame
    if isImageLeftSide {
         customFrame.origin.x = customFrame.origin.x + 25   //assuming 25 is pixels by which your image should be shifted
    }
    else {
         customFrame.origin.x = customFrame.origin.x - 25
    }
    shape.frame = customFrame
    isImageLeftSide = ! isImageLeftSide
}

接下来,您只需检查状态并更改形状视图的x坐标。如果它是左侧增加x坐标,如果它是右侧减少x坐标