更新按钮上的标签单击

时间:2017-07-12 11:41:56

标签: swift3 uibutton uilabel xcode8 ios10

我的主页上有两个按钮作为左右箭头,每次点击一个按钮时,UILabel会通过数组let names = ["John, Smith, "Ahmed", "Jack", "Kathy"]更新。我有两个UIActions作为rightArrowClicked和leftArrowClicked。最初,标签应显示为John,左箭头禁用,这将由leftArrow的isHidden属性完成,同样当值为Kathy时,则应禁用rightArrow。除此之外,我还需要将另一个标签wrt更新为名称值,例如john可以具有“可爱”的值,并且kathy为“漂亮”,并且这些值来自我通过{{1添加的外部库这是在该类的函数中生成的。任何想法我会怎么做?

2 个答案:

答案 0 :(得分: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

}

答案 1 :(得分: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)")
    }