首页 文章

更新按钮上的标签单击

提问于
浏览
1

我的主页上有两个按钮作为左右箭头,每次点击一个按钮,UILabel都会通过数组更新,例如 let names = ["John, Smith, "Ahmed", "Jack", "Kathy"] . 我有两个UIActions作为rightArrowClicked和leftArrowClicked . 最初,标签应显示为John,禁用左箭头,'ll be done by the isHidden property of leftArrow and likewise when the value is Kathy then rightArrow should be disabled. Along with that i also need to update another label w.r.t to the name value e.g john can have a value of 816167 , and kathy as 816168 and these values are coming from an external library which i' ve通过 cocoapods 添加,这是在该类的功能中生成的 . 任何想法我会怎么做?

2 回答

  • 1

    这是您需要的具有简单逻辑的代码

    let names = ["John", "Smith", "Ahmed", "Jack", "Kathy"]
    var currentIndex = 0
    leftButton.isHidden = true
    
    @IBAction func left(_ sender: Any) {
        currentIndex --
        label.text = names[currentIndex]
    
        if currentIndex == 0 {
            leftButton.isHidden = true
        }
    
        rightButton.isHidden = false
    
    
    }
    
    @IBAction func right(_ sender: Any) {
        currentIndex ++
        label.text = names[currentIndex]
    
        if currentIndex == names.count - 1 {
            rightButton.isHidden = true
        }
    
        leftButton.isHidden = false
    
    }
    
  • 0

    您可以尝试如下,并在viewDidLoad方法中调用updateButtonsState()

    let names = ["John", "Smith", "Ahmed", "Jack", "Kathy"]
    let nature = ["cute", "pretty", "cute", "pretty", "cute"]
    var currenIndex = 0
    
    @IBAction func leftBtnClick(_ sender: UIButton) {
            currenIndex = currenIndex - 1
            updateButtonsState()
    
        }
        @IBAction func rignthBtnClick(_ sender: UIButton) {
            currenIndex = currenIndex + 1
            updateButtonsState()
        }
        func updateButtonsState() {
            leftBtn.isEnabled = currenIndex > 0 ? true : false
            rightBtn.isEnabled = currenIndex < names.count - 1 ? true : false
            if currenIndex >= 0 && currenIndex < names.count {
                lblName.text = names[currenIndex]
                lblNameWithNature.text = nature[currenIndex]
            }
            print("currenIndex == \(currenIndex)")
        }
    

相关问题