点击按钮时如何自动递增和递减计数

How to auto increment and decrement count when I tap Button

我有两个按钮,分别称为“+”和“-”。

如果我点击“+”按钮,我必须将计数值增加到最大值“7”,如果我点击“-”按钮,我必须减少计数值,如果该值达到“1”,则该值必须不会改变,因为我至少有“1”作为默认值。

这是我的示例代码:

@IBAction func seat_btns(sender: AnyObject) {

    if sender.tag == 10 {

        let i : Int!

        let s = self.seatNumberLabel.text
        if let x = Int(s!) {
            i = x + 1
            self.seatNumberLabel.text = i.description

        }

    }
    else if sender.tag == 20 {
        let s = self.seatNumberLabel.text
        let i : Int!

        if let x = Int(s!) {
            i = x - 1
            self.seatNumberLabel.text = i.description

    }

    }
}

最多 7 个

i = max(1, min(x + 1, 7))

至少 1

 i = max(1, min(x - 1, 7))

已编辑:

if sender.tag == 10 {

        let i : Int!

        let s = self.seatNumberLabel.text
        if let x = Int(s!) {
                i = max(1, min(x + 1, 7)
                self.seatNumberLabel.text = i.description
        }

    }
    else if sender.tag == 20 {
        let s = self.seatNumberLabel.text
        let i : Int!

        if let x = Int(s!) {
                i = max(1, min(x - 1, 7)
                self.seatNumberLabel.text = i.description
        }
}

简单的 if 检查可以帮助你

@IBAction func seat_btns(sender: AnyObject) {

    if sender.tag == 10 {

        let i : Int!

        let s = self.seatNumberLabel.text
        if let x = Int(s!) {
            if (x < 7) {
                i = x + 1
                self.seatNumberLabel.text = i.description
            }
        }

    }
    else if sender.tag == 20 {
        let s = self.seatNumberLabel.text
        let i : Int!

        if let x = Int(s!) {
            if (x > 1) {
                i = x - 1
                self.seatNumberLabel.text = i.description
            }
        }

    }
}