点击已选择的段时检测事件

时间:2015-05-14 12:41:17

标签: ios swift uisegmentedcontrol

嗨我想在触摸已经选定的片段时获得活动。

我已实施以下解决方案

import UIKit

class MARSSegmentController: UISegmentedControl {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
    // Drawing code
    }
    */

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        let oldValue:NSInteger = self.selectedSegmentIndex
        super.touchesBegan(touches, withEvent: event)
        if oldValue == self.selectedSegmentIndex{
            sendActionsForControlEvents(UIControlEvents.ValueChanged)
        }
    }    
} 

这工作正常,但如果我点击非选定的段,则ValueChanged事件会被执行两次。

实施点按手势无效。表示当我点击未选择的片段时,它会在使用点击手势时显示旧的所选片段。

如果有任何解决方案,请建议。

3 个答案:

答案 0 :(得分:7)

我意识到这是一个较旧的问题,但我遇到了同样的问题,我需要检测是否选择了现有的段以及所选的段更改。

上面的解决方案很接近,但这对我有用。在touchesBegan上捕获现有的选定段索引,然后在touchesEnded中,将旧值与当前选定的段索引进行比较。如果它们相同,我手动触发.ValueChanged事件。注意:这是Swift 2.0语法。

class SegmentedControlExistingSegmentTapped : UISegmentedControl
{
    // captures existing selected segment on touchesBegan
    var oldValue : Int!

    override func touchesBegan( touches: Set<UITouch>, withEvent event: UIEvent? )
    {
        self.oldValue = self.selectedSegmentIndex
        super.touchesBegan( touches , withEvent: event )
    }

    // This was the key to make it work as expected
    override func touchesEnded( touches: Set<UITouch>, withEvent event: UIEvent? )
    {
        super.touchesEnded( touches , withEvent: event )

        if self.oldValue == self.selectedSegmentIndex
        {
            sendActionsForControlEvents( .ValueChanged )
        }
    }
}

答案 1 :(得分:1)

只放self.nameSegmentedControl.isMomentary = true

如果您的方法与valueChanges相关联,则会检测到点按。

答案 2 :(得分:0)

我认为你的问题在于 app.UseOAuthBearerAuthentication(bearer => { bearer.SecurityTokenValidators = new List<ISecurityTokenValidator>() { new CustomSecurityValidationToken() }; bearer.AutomaticAuthentication = true; bearer.Notifications = new OAuthBearerAuthenticationNotifications() { SecurityTokenReceived = context => { return Task.FromResult(0); }, MessageReceived = context => { return Task.FromResult(0); }, SecurityTokenValidated = context => { return Task.FromResult(0); }, AuthenticationFailed = context => { context.Response.Redirect("Home/Error?message=" + context.Exception.Message); return Task.FromResult(0); } }; }); if oldValue == self.selectedSegmentIndex而永远都会返回true。因此,您只需要使用let oldValue:NSInteger = self.selectedSegmentIndex更改if条件,其中selectedValue是您考虑选择分段的值