【问题标题】:How to use IF statement for UILabel and String in Swift?如何在 Swift 中对 UILabel 和 String 使用 IF 语句?
【发布时间】:2019-11-14 01:38:52
【问题描述】:

如果 timeInWord == "twelveAM" {

我收到以下错误:二元运算符“==”不能应用于“UILabel”和“字符串”类型的操作数

你能解决这个问题吗?

import UIKit

class ViewController: UIViewController {

    let scrollView = DScrollView()
    let scrollViewContainer = DScrollViewContainer(axis: .vertical, spacing: 10)
    let scrollViewElement = DScrollViewElement(height: 1200, backgroundColor: .lightGray)

    let timeComponents = ["twelveAM": "12 AM", "oneAM": "1 AM", "twoAM": "2 AM", "threeAM": "3 AM", "fourAM": "4 AM", "fiveAM": "5 AM", "sixAM": "6 AM", "sevenAM": "7 AM", "eightAM": "8 AM", "nineAM": "9 AM", "tenAM": "10 AM", "elevenAM": "11 AM", "Noon": "Noon", "onePM": "1 PM", "twoPM": "2 PM", "threePM": "3 PM", "fourPM": "4 PM", "fivePM": "5 PM", "sixPM": "6 PM", "sevenPM": "7 PM", "eightPM": "8 PM", "ninePM": "9 PM", "tenPM": "10 PM", "elevenPM": "11 PM", "midnight": "12 AM"]

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white


        view.addScrollView(scrollView, withSafeArea: .withSpaceForHeadline, hasStatusBarCover: false, statusBarBackgroundColor: .white, container: scrollViewContainer, elements: [scrollViewElement])


        for (timeInWord, timeInNumber) in timeComponents{
            let timeInWord = UILabel()
            timeInWord.text = timeInNumber
            scrollViewElement.addSubview(timeInWord)
            if timeInWord == "twelveAM" {
                timeInWord.edgeTo(scrollViewElement, safeArea: .twelveAm)
            }
            else {
                timeInWord.edgeTo(scrollViewElement, safeArea: .followingHour)
            }
        }
    }
}

【问题讨论】:

    标签: swift string if-statement uilabel


    【解决方案1】:

    timeInWordUILabeltimeInWord.textString。因此,如果要将标签中的文本与某个常量字符串进行比较,则应使用 if timeInWord.text == "twelveAM"。您可以通过在 Xcode 中单击它来获取任何变量的类型。确保类型符合您的预期。

    【讨论】:

      【解决方案2】:

      您可以通过以下方式解决此问题:

      for (timeInWord, timeInNumber) in timeComponents{
          let timeInWordLabel = UILabel()
          timeInWordLabel.text = timeInNumber
          scrollViewElement.addSubview(timeInWordLabel)
          if timeInWord == "twelveAM" {
              timeInWordLabel.edgeTo(scrollViewElement, safeArea: .twelveAm)
          }
          else {
              timeInWordLabel.edgeTo(scrollViewElement, safeArea: .followingHour)
          }
      }
      

      【讨论】:

        【解决方案3】:

        正如 josh 所提到的,您不能将 UILable 与字符串进行比较。您应该检查 UILablel 的文本。即 UILabel.Text == "某事"

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-30
          • 2021-09-30
          • 2020-12-02
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 2016-05-20
          相关资源
          最近更新 更多