如何在某些条件下更改以编程方式创建的UIButton的标题和操作

时间:2016-03-04 20:34:06

标签: ios swift uibutton uicontrolstate

我在ViewController上以编程方式创建了UIButton。我想根据条件对同一个按钮执行不同的操作,并且还想更改标题。

首先我创建这样的按钮:

func createButton(buttonTitle: String,buttonAction: Selector) -> UIButton{
    let button   = UIButton(type: UIButtonType.System) as UIButton
    button.frame = CGRectMake(0, 0, 414, 65)

    button.setTitle(buttonTitle, forState: UIControlState.Normal)
    button.addTarget(self, action:buttonAction, forControlEvents: UIControlEvents.TouchUpInside)
    button.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)
    button.titleLabel?.font = UIFont(name: Variables.MONTESERRAT_REGULAR, size: 20.0)

    button.backgroundColor = UIColor().blueColor()       //top
    button.titleEdgeInsets = UIEdgeInsetsMake(0.0,10.0, 10.0, 0.0)
      return button
}

然后我就像这样展示

override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height))

    if(active == true){
       bottomButton = createButton("UNPUBLISH", buttonAction: "unPublishToServer")
    }else if(active == false){
        bottomButton = createButton("PUBLISH", buttonAction: "publishToServer")
    }else{
        bottomButton = createButton("Request", buttonAction: "requestItem")
    }

    footerView.addSubview(bottomButton!)
    return footerView
}

然后在来自服务器的某些消息或条件我正在改变按钮

func publishTripToServer(){
    dispatch_async(dispatch_get_main_queue()) {
        self.bottomButton?.setTitle("UNPUBLISH", forState: UIControlState.Normal)
    }
}

func unPublishTripToServer(){
    dispatch_async(dispatch_get_main_queue()) {
        self.bottomButton?.setTitle("PUBLISH", forState: UIControlState.Normal)
    }
}

我遇到的问题首先是当我点击发布或取消发布时,它会在标题后面显示一些背景颜色。第二个问题是按钮没有改变动作。

1 个答案:

答案 0 :(得分:1)

我不确定你对背景颜色问题的意思。

但对于你的按钮,这样的事情不起作用吗?

func publishTripToServer(){

    self.bottomButton = createButton("UNPUBLISH", buttonAction: "unPublishToServer")
}



 func unPublishTripToServer(){
     self.bottomButton = createButton("PUBLISH", buttonAction: "publishToServer")
}

我不知道为什么你之前尝试更新后台线程上的按钮标题,但你不应该异步更新ui元素。

你的按钮动作没有改变的原因是你从未告诉它改变 - 你只是改变了标题

相关问题