0

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

首先,我创建这样的按钮:

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

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

4

1 回答 1

1

我不确定您对背景颜色问题的含义。

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

func publishTripToServer(){

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



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

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

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

于 2016-03-04T20:54:31.053 回答