UISegmentedControl选择Segment始终为-1

时间:2014-08-01 14:54:27

标签: xcode swift uisegmentedcontrol

我将UISegmentedControl子类化,以便触发valueChanged方法,该方法工作正常。现在,当我选择一个段时,索引始终为-1。 我在Xcode 6 beta 4上,我找不到我做错了什么。 子类:

import UIKit

class MySegCotrl: UISegmentedControl {

init(coder aDecoder: NSCoder!)  {
    super.init(coder: aDecoder)
}

override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
    let current = self.selectedSegmentIndex
    super.touchesBegan(touches, withEvent: event)
    println("Current:\(current)")
    println("Self.selectedSegmentIndex:\(self.selectedSegmentIndex)")
    if current == self.selectedSegmentIndex {
        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
}

}

我的UIViewController类中的valueChanged方法

@IBOutlet var segCotrRelevanz: MySegCotrl!

@IBAction func relevanChanged(sender: AnyObject) {

    println("sender.selectedSegmentIndex:\(sender.selectedSegmentIndex)")
    println("segCotrRelevanz.selectedSegmentIndex:\(segCotrRelevanz.selectedSegmentIndex)")

    if sender.selectedSegmentIndex == segCotrRelevanz.selectedSegmentIndex {
        println("Same")
    }

}

输出:

Current:-1
Self.selectedSegmentIndex:-1
sender.selectedSegmentIndex:-1
segCotrRelevanz.selectedSegmentIndex:-1
Same

1 个答案:

答案 0 :(得分:0)

尝试更改方法touchchesBegan not touchesEnded,保留所有应该是:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    let current = self.selectedSegmentIndex
    super.touchesBegan(touches, withEvent: event)
    println("Current:\(current)")
    println("Self.selectedSegmentIndex:\(self.selectedSegmentIndex)")
    if current == self.selectedSegmentIndex {
        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
}