簡體   English   中英

如何在某些情況下更改以編程方式創建的UIButton的標題和操作

[英]How to change the title and action of a programmatically created UIButton on some condition

我已經在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)
    }
}

我遇到的問題是,當我單擊“發布”或“取消發布”時,它首先在標題后面顯示了一些背景色。 第二個問題是按鈕未更改操作。

我不確定您對背景色問題的含義。

但是對於您的按鈕,這樣的操作不起作用嗎?

func publishTripToServer(){

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



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

我不知道您為什么以前嘗試在后台線程上更新按鈕標題,但是您不應該異步更新ui元素。

而且您的按鈕動作沒有改變的原因是您從未告訴過要改變-您只是改變了標題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM