Binary operator '==' cannot be applied to operands of type 'UILabel?' and 'String'

前端 未结 4 789
天涯浪人
天涯浪人 2021-01-29 16:46

Error : Binary operator \'==\' cannot be applied to operands of type \'UILabel?\' and \'String\'


import UIKit

class ViewController: UIViewController {
  let So         


        
4条回答
  •  萌比男神i
    2021-01-29 17:14

    An UIButton exposes its label through an UILabel that manage the drawing of its text. Thus change:

    let hardness = sender.titleLabel
    

    to

    let hardness = sender.titleLabel.text
    

    UIKit docs says:

    UIButton

    var titleLabel: UILabel?

    A view that displays the value of the currentTitle property for a button.

    and:

    UILabel

    var text: String?

    The current text that is displayed by the label.

    There is also a more direct way using the currentTitle:

    UIButton

    var currentTitle: String?

    The current title that is displayed on the button.

    Thus:

    let hardness = sender.currentTitle
    

    will also work.

提交回复
热议问题