如何在Swift中为UILabel和String使用IF语句?

问题描述 投票:0回答:3

如果timeInWord ==“ twelveAM” {

我收到以下错误:二进制运算符'=='无法应用于'UILabel'和'String'类型的操作数

您能解决这个问题吗?

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
3个回答
0
投票

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


0
投票

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

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)
    }
}

0
投票

正如乔什所说,您不能将UILable与字符串进行比较。您应该检查UILablel的文本。即UILabel.Text ==“ something”

© www.soinside.com 2019 - 2024. All rights reserved.