如何以编程方式向按钮添加操作。我需要在mapView中为按钮添加show动作。感谢
GetBar(fooId).Result
答案 0 :(得分:25)
您可以使用以下代码
`
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle("Click Me", for: .normal)
btn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
btn.tag = 1
self.view.addSubview(btn)
采取行动
@objc func buttonAction(sender: UIButton!) {
let btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
dismiss(animated: true, completion: nil)
}
}
答案 1 :(得分:16)
let button = UIButton(type: UIButtonType.Custom) as UIButton
button.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
//then make a action method :
func action(sender:UIButton!) {
print("Button Clicked")
}
答案 2 :(得分:9)
您可以创建这样的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchDragInside];
[button setTitle:@"Test Headline Text" forState:UIControlStateNormal];
button.frame = CGRectMake(20, 100, 100, 40);
[self.view addSubview:button];
自定义操作
-(void)buttonAction {
NSLog(@"Press Button");
}
请您创建这样的按钮
let button = UIButton()
button.frame = CGRect(x: self.view.frame.size.width - 20, y: 20, width: 100, height: 100)
button.backgroundColor = UIColor.gray
button.setTitle("ButtonNameAreHere", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
自定义操作
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
答案 3 :(得分:8)
你需要像穆罕默德建议的那样为按钮添加一个目标
button.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
但你也需要一种方法来实现这一行动
func action(sender: UIButton) {
// Do whatever you need when the button is pressed
}
答案 4 :(得分:1)
除上述内容外,新的ios14引入了
if #available(iOS 14.0, *) {
button.addAction(UIAction(title: "Click Me", handler: { _ in
print("Hi")
}), for: .touchUpInside)
} else {
// Fallback on earlier versions
}
答案 5 :(得分:0)
对于Swift 4,请使用以下内容:
button.addTarget(self, action: #selector(AwesomeController.coolFunc(_:)), for: .touchUpInside)
//later in your AswesomeController
@IBAction func coolFunc(_ sender:UIButton!) {
// do cool stuff here
}
答案 6 :(得分:-1)
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton()
btn.frame = CGRectMake(10, 10, 50, 50)
btn.setTitle("btn", forState: .Normal)
btn.setTitleColor(UIColor.redColor(), forState: .Normal)
btn.backgroundColor = UIColor.greenColor()
btn.tag = 1
btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
self.view.addSubview(btn)
}