如何使用标签文本(Int)值来写条件

时间:2019-06-27 12:34:20

标签: ios swift if-statement label

我从服务器获取日期(响应),并将该值存储在标签中,并且如果使用的叶子应该大于总数,我想使用标签编写if条件,我希望允许下一个Viewcontroller离开,我得到了错误

我的情况是,“总叶子”和“用过的叶子”将通过服务器动态产生,并且如果我们应用2天将转换为(总叶子)的叶子,则数字应类似于总共5个叶子(总叶子)“ 3英寸,并且使用过的叶子标签文本将替换为2这样的格式,它将起作用,并且如果在这种情况下叶子总数也为0,则应该显示错误消息

我的代码是

 if  ((self.totalLeaves.text) > (self.usedLeavesLbl.text)) {
            let alert = UIAlertController(title: "Alert", message: "You Dont have leaves to Apply", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
                switch action.style{
                case .default:
                    print("Please Enter Details")

                case .cancel:
                    print("cancel")

                case .destructive:
                    print("destructive")
                }}))
            self.present(alert, animated: true, completion: nil)
        }
     else {
        // Fallback on earlier versions
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "ApplyLeavesViewController") as! ApplyLeavesViewController
        self.navigationController?.pushViewController(secondViewController, animated: true)
    }

我的错误是编译错误无法转换类型为'String'的值?到预期的参数类型'UIContentSizeCategory' 从解包的“字符串”值构造“ UIContentSizeCategory”

2 个答案:

答案 0 :(得分:1)

只需将字符串转换为int进行比较

 if  (Int(self.totalLeaves.text) == 0 || (Int(self.totalLeaves.text) > Int(self.usedLeavesLbl.text))) {
    ...
    ...
}

答案 1 :(得分:1)

检查以下答案!

    guard let totalLeaves = self.totalLeaves.text,
        let usedLeaves = self.usedLeavesLbl.text else {
            //totalLeaves or usedLeavesLbl is nil
            return
    }

    guard let intTotalLeaves = Int(totalLeaves),
        let intUsedLeaves = Int(usedLeaves) else {
            //totalLeaves or usedLeaves is not contains integer values
            return
    }

    if (intTotalLeaves == 0) || (intTotalLeaves > intUsedLeaves) {
        //Display your error message here
    } else {
        //redirect to another view controller
    }