Swift获取UIPanGestureRecognizer中的Button标题

时间:2014-12-12 21:25:20

标签: swift uibutton ios8 uipangesturerecognizer

我通过此功能在我的视图中创建了各种按钮,当UIPanGestureRecognizer出现时.Changed:我想获得按钮的标题

    var searchIndex:Int!

    func CreateButtonWithIndex(index:Int) {

    let newButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
    newButton.setTitle("Button \(index+1)", forState: UIControlState.Normal)
    newButton.tag = index+1;

//Mark: - UIPanGesture
    var pan = UIPanGestureRecognizer(target:self, action:"pan:")
    pan.maximumNumberOfTouches = 1
    pan.minimumNumberOfTouches = 1
    newButton.addGestureRecognizer(pan)
    self.searchIndex = pan.view?.tag
    self.view.addSubview(newButton)
}

//Mark: - pan

func pan(rec:UIPanGestureRecognizer) {

    var p:CGPoint = rec.locationInView(self.view)

    var center:CGPoint = CGPointZero

    switch rec.state {
    case .Began:
        println("began")
        selectedView = view.hitTest(p, withEvent: nil)
        if selectedView != nil {
           self.view.bringSubviewToFront(selectedView!)
        }

    case .Changed:
          let subviews = self.view.subviews as [UIView]
            for v in subviews {
                if let button = v as? UIButton {
                   if button.tag == self.searchIndex {
                                println("\(button.titleLabel!.text)")
                               }}} 
等等...... 我试图以这种方式获取按钮的名称,但我没有按钮的真实标题

1 个答案:

答案 0 :(得分:1)

UIGestureRecognizer有一个属性view,它是附加到的视图。您可以使用它来获取按钮,然后在按钮中查询其标题:

func pan(rec:UIPanGestureRecognizer) {
    if let button = rec.view as? UIButton {
        if let title = button.titleForState(.Normal) {
            println(title)
        }
    }
}