iphone - UISegmentedControl 抛出异常

标签 iphone ios objective-c cocoa-touch methods

当单击下面的按钮操作时,出现异常:

-[UIRoundedRectButton selectedSegmentIndex]:无法识别的选择器发送到实例 0x8178b90
'

(它也在头文件中初始化为 - (IBAction)genderBtn:(id)sender; )。

我不知道是否应该以某种方式将其初始化为另一个方法或全局初始化。任何方法想法将不胜感激。

- (IBAction)submitButton:(id)sender {

  double BAC=0;

  //  NSString *weight=weightTextField.text;

  //Other variables etc.

UISegmentedControl *gender = (UISegmentedControl *)sender;


   UIButton *gender = (UIButton *)sender;


if (gender.selected == 0 ) {



} else if (gender.selected = 1){



}


UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Your Results:"
                                          message:[NSString stringWithFormat:@" Your Percentage is: "]
                                         delegate:self
                                cancelButtonTitle:@"OK"
                                otherButtonTitles:nil];

[alertMessage show];
}

最佳答案

该错误表明,尽管您认为发送者值是 UISegmentedControl,但事实并非如此。这是一个 UIRoundedRectButton。结果是您最终将一条只有 UISegmentedControl 实现的消息发送到 UIRoundedRectButton,因此它无法识别选择器。确保此操作连接到正确类型的按钮。


编辑:好的。我之前看过你的代码。我认为问题是您使用了普通的 UIButton 而不是 UISegmentedControl,但问题似乎确实是您根本不应该使用发送者参数

我认为你有一个 UISegmentedControl 供用户选择某些内容,还有一个 UIButton 供他们在完成选择后点击。问题是您询问发送者参数(即提交按钮)UISegmentedControl 的选择状态是什么。您需要将 UISegmentedControl 存储在属性中,并在提交方法中使用它来获取 selectedSegmentIndex。

- (IBAction)submitButton:(id)sender {

    double BAC=0;

    //NSString *weight=weightTextField.text;

    //Other variables etc.

    UISegmentedControl *gender = self.segmentedControl;


    if (gender.selectedSegmentIndex == 0 ) {
        //something
    } else if (gender.selectedSegmentIndex == 1){
        //something
    }

    UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Your Results:"
                                          message:[NSString stringWithFormat:@" Your Percentage is: "]
                                         delegate:self
                                cancelButtonTitle:@"OK"
                                otherButtonTitles:nil];

    [alertMessage show];
}

提交按钮在按下时调用此按钮,并从存储在属性中的分段控件中获取选定的索引。

@property (weak, nonatomic) IBOutlet UISegmentedControl* segmentedControl; //goes in @interface

@synthesize segmentedControl = _segmentedControl; //goes in @implementation

将此 IBOutlet Hook 到分段控件并使用它。

关于iphone - UISegmentedControl 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14245942/

相关文章:

ios - 在纵向和横向中使用 objective-c 中的图像设置自定义键盘

ios - 在iOS中的Facebook登录中检查是否已在此应用程序中注册

ios - Xcode bot 安装链接请求超时

iphone - iOS 上的数据保护

iphone - 处理父 View 触摸

iphone - 为什么 UIWebView 实例不调用 scrollViewDidScroll?

ios - SwiftUI 耗费了我一上午的时间,只是构建了一个小按钮,请救救我

iphone - 在现有屏幕上显示小 View /对话框的最佳方式?

iphone - 将后退按钮添加到 View Controller

ios - 在 View 之间滑动时更改标签文本颜色