![](/img/trans.png)
[英]How to add UIViewController as target of UIButton action created in programmatically created UIView?
[英]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.