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

时间:2022-08-22 12:11:40

Im trying to make a custom switch button with an image view that moves to the right of its container when clicked and to the left of the container when clicked again. What code do I need for this?

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

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 is the image view that should be moved left to right.

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

1 个解决方案

#1


0  

Maintain a bool variable for maintaining the state.

保持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
}

Next all you have to do this check the state and change x coordinate of your shape view. If it is to left side increase the x coordinate and if it is to right side decrease x coordinate

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

#1


0  

Maintain a bool variable for maintaining the state.

保持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
}

Next all you have to do this check the state and change x coordinate of your shape view. If it is to left side increase the x coordinate and if it is to right side decrease x coordinate

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