发生SwipeGesture时更改UILabel的Text和ImageView

时间:2018-07-19 13:24:59

标签: ios swift

我正在实现火种克隆,并且试图弄清楚在发生左滑动手势时如何更改UILabel文本和ImageView图像。

我可以一次刷卡,但如何进行3-4次刷卡?

这是我到目前为止所拥有的。

@IBOutlet weak var loginImageView: UIImageView!
    let loginText = ["Discover new and interesting people near by" , "Swipe Right to meet new" , "Hey how are you?"]
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        updateCornerRadius()
        updatefbcornerRadius()
        updateText()
    }

    @IBOutlet weak var textLabel: UILabel!{
        didSet{
            updateText()
        }
    }

    private func updateText(){
        textLabel.numberOfLines = 0
        textLabel.adjustsFontSizeToFitWidth = true;
        textLabel.minimumScaleFactor = 0.5
    }
    @IBOutlet weak var swipePictureView: UIView! {
        didSet{
            let swipe = UISwipeGestureRecognizer(target: self, action: #selector(nextImage))
            swipe.direction = .left
            swipePictureView.addGestureRecognizer(swipe)
        }
    }

    @objc func nextImage(_ gesture: UISwipeGestureRecognizer){
            textLabel.text = "Swipe right to meet new"
            loginImageView.image = UIImage(named: "tinder2")

    }

故事板看起来像这样。

enter image description here

  

用于滑动的UIView从顶部一直到“使用   大学编号”

2 个答案:

答案 0 :(得分:0)

尝试此方法。创建数组的字典。带有图像的文字。

let data = [["text":"Discover new and interesting people near by","image":"tinder1"],["text":"Swipe Right to meet new","image":"tinder2"],["text":"Hey how are you?","image":"tinder3"]]
var currentIndex = 0

@objc func nextImage(_ gesture: UISwipeGestureRecognizer){
    currentIndex += 1
    guard currentIndex < data.count else { return }
    if let textValue = data[currentIndex]["text"]{
        print(text)
        textLabel.text = textValue 
    }
    if let image = data[currentIndex]["image"]{
        print(image)
        loginImageView.image = UIImage(named: "\(image)")
    }
}

不要忘记处理找不到文本和图像的地方。您可以设置默认图像或文本。

答案 1 :(得分:0)

问题:-每次发生滑动时,您每次都会在标签中设置“向右滑动以结识新朋友”文本。您的滑动操作正常,但操作不正确。

解决方案:- 您必须跟踪滑动的计数并根据计数更新textLabel的文本。

var count = -1
@objc func nextImage(_ gesture: UISwipeGestureRecognizer){
    count = count + 1
    if count < loginText.count {
        textLabel.text = loginText[count]
    } 

    //Arrimage contains name of images
    if count < arrImage.count {
        loginImageView.image = UIImage(named: arrImage[count])
    }
}

只需在nextImage函数中放置一个断点,然后在屏幕上滑动即可看到,每次滑动该函数都会被调用。