Swift UIButton .setTitle无效

时间:2015-09-24 21:07:48

标签: swift cocoa-touch uibutton

我在VC上以编程方式创建了一组按钮。我在创建按钮时添加了按钮的目标,并且在被调用的函数中我正在更改背景图像并尝试删除标题。但是,标题没有改变,但背景图像正在改变,这对我来说没有意义。

func createButton(xPos: Int, yPos: Int, width: Int, height: Int, buttonIndex: Int) -> UIButton {
    var button = UIButton()
    button.frame = CGRect(x: xPos , y: yPos, width: width, height: height)
    button.userInteractionEnabled = true
    button.layer.masksToBounds = true
    var buttonImage = UIImage(named: "Display_Icon")
    button.tag = buttonIndex
    button.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
    button.setTitle("\(buttonIndex)", forState: UIControlState.Normal)
    var titleColor = UIColor(red: 0.0, green: 104/255.0, blue: 178/255.0, alpha: 1.0)
    button.setTitleColor(titleColor, forState: UIControlState.Normal)
    button.addTarget(self, action: "screenSelected:", forControlEvents: UIControlEvents.TouchUpInside)
    return button
}

func screenSelected(button: UIButton!) {

    if hasError { hasError = false; return }
    let screenIndex = button.titleLabel!.text!

    if contains(buttonsSelectedArray, screenIndex) {
        return
    }

    buttonsSelectedArray.append(screenIndex)
    var buttonImage = UIImage(named: "DisplaySelected_Icon")
    button.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
    button.setTitle("", forState: UIControlState.Normal)
    var titleColor = UIColor.clearColor()
    button.setTitleColor(titleColor, forState: UIControlState.Normal)

2 个答案:

答案 0 :(得分:0)

试试这个,

你在旧方法(Obj-c)中添加目标按钮的问题

func createButton(xPos: Int, yPos: Int, width: Int, height: Int, buttonIndex: Int) -> UIButton {
    ....
    ....
button.addTarget(self, action: #selector(UIViewController. screenSelected(_:)), for: UIControlEvents.touchUpInside)
    return button
}  





@IBAction func screenSelected(button: UIButton!) {

    if hasError { hasError = false; return }
    let screenIndex = button.titleLabel!.text!

    if contains(buttonsSelectedArray, screenIndex) {
        return
    }

    buttonsSelectedArray.append(screenIndex)
    var buttonImage = UIImage(named: "DisplaySelected_Icon")
    button.setBackgroundImage(buttonImage, forState: .normal)
    button.setTitle("", forState: .normal)
    var titleColor = UIColor.clearColor()
    button.setTitleColor(titleColor, forState: .normal)
}

答案 1 :(得分:-1)

您需要像这样设置按钮标题

  

button.setTitle(" Button Title Here",for:UIControlState.normal)

IOS不再支持使用

  

button.titleLabel?.text ="按钮标题"

因为您需要使用其选定,正常,突出显示或其他任何位置的UIControlState设置标题。

请参阅此https://developer.apple.com/reference/uikit/uibutton/1624018-settitle?language=objc

中的文档