UIPanGestureRecognizer 中的 Swift 获取按钮标题

Posted

技术标签:

【中文标题】UIPanGestureRecognizer 中的 Swift 获取按钮标题【英文标题】:Swift Get Button title in UIPanGestureRecognizer 【发布时间】:2014-12-12 21:25:20 【问题描述】:

我通过这个函数在我的视图中创建了我的各种按钮,当 UIPanGestureRecognizer 以防万一时。更改:我想获取按钮的标题

    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】:

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

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

【讨论】:

以上是关于UIPanGestureRecognizer 中的 Swift 获取按钮标题的主要内容,如果未能解决你的问题,请参考以下文章

部分标题视图中的 UIPanGestureRecognizer 影响 UITableViewCell

SKScene 中的 UIPanGestureRecognizer

UIPanGestureRecognizer 状态结束后动画中的小问题

游乐场中的 UIPanGestureRecognizer

在UIPanGestureRecognizer中的框架上的UIView.animate

UIPanGestureRecognizer中的Velocity和translation开始状态