如何在按钮上更改操作的目标 - Swift

时间:2016-01-15 02:46:39

标签: ios xcode swift

import Foundation
import MapKit

class CustomAnnotationView : MKPinAnnotationView
{
    let selectedLabel:UILabel = UILabel.init(frame:CGRectMake(0, 0, 250, 125))
    let Button:UIButton = UIButton.init(frame:CGRectMake(0, 0, 100, 38))

override func setSelected(selected: Bool, animated: Bool)
{
    super.setSelected(false, animated: animated)

    if(selected)
    {
        selectedLabel.text = annotation!.title!
        selectedLabel.center.x = 0.5 * self.frame.size.width
        selectedLabel.center.y = -0.5 * selectedLabel.frame.height

        self.addSubview(selectedLabel)

        Button.backgroundColor = UIColor.yellowColor()
        Button.setTitle("Press", forState: UIControlState.Normal)


        //the code below here //
var storyboard = UIStoryboard(name: "Main", bundle: nil)
            let Map = storyboard.instantiateViewControllerWithIdentifier("Map")
            Button.addTarget(Map, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

        //self.view.addSubview(button)
        Button.center.x = 0.5 * self.frame.size.width + 10
        Button.center.y = selectedLabel.center.y
        self.addSubview(Button)

    }
    else
    {
        selectedLabel.removeFromSuperview()
    }

}

//这在Map.swift中

    func buttonAction () {
        print("button pressed")
    }
}

而不是使用Button.addTarget(自我... 正如我在自定义类中编码一样。 如何让它运行该动作? 我还将故事板的名称也设置为右侧面板上的Main,与Map相同。

3 个答案:

答案 0 :(得分:0)

Map方法发布后,setSelected被释放。你应该通过某种东西(属性,全局变量,......)来处理Map

答案 1 :(得分:0)

嗯,一个可能的解决方案就是在按钮上添加一个轻击手势识别器,可以用以下代码完成:

    let tap = UITapGestureRecognizer(target: self, action: Selector("actionTap:"))
    tap.delegate = self
    Button.addGestureRecognizer(tap)

然后你可以让视图控制器符合UIGestureRecognizerDelegate的类。

此外,创建一个功能,可以按下按钮时执行的操作,并将其命名为" actionTap"像这样:

    func actionTap(sender: UITapGestureRecognizer? = nil) {
    // Implement what you want the button to do here.
}

答案 2 :(得分:0)

在CustomAnnotationView类中添加一个块:

  

var tapProccess:(() - >())?

在您的动作功能

func buttonAction () {
    self.tapProccess?()
}

并实施它:

    let customAnno = CustomAnnotationView()
    customAnno.tapProccess = {()->() in
        // do some thing
    }