【问题标题】:custom properties for UIButton (iphone sdk)UIButton 的自定义属性(iphone sdk)
【发布时间】:2010-09-07 22:06:36
【问题描述】:

我为 UIButton 创建了一个子类,并希望将自定义属性传递给它。但是,它不起作用,我从那以后读到子类化 UIButton 不是一个好主意。

我的问题是如何将自定义属性分配给按钮?我正在创建一个按钮,该按钮被放置在分组表的标题视图中。我想将部分编号传递给该按钮。我已经成功地在每一行中使用了一个 UISwitch,但不能对 UIButton 使用相同的方法。

所以我创建了一个按钮

MattsButtonClass *button = [MattsButtonClass buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(240, 15, 45, 30);
button.MFsectionNo = section; //this would be 1, 2 etc
//etc

那么我该怎么做呢?你会看到我的 UIbutton 有一个子类,看起来像这样

//.h file
@interface MattsButtonClass : UIButton {
    int MFsectionNo;
}

@property (nonatomic) int MFsectionNo;

@end

//.m file
@implementation MattsButtonClass

@synthesize MFsectionNo;


@end

上面的错误是

-[UIRoundedRectButton MFsectionNo:]: unrecognized selector sent to instance 0x5673650
2010-09-07 22:41:39.751 demo4[67445:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIRoundedRectButton MFsectionNo:]: unrecognized selector sent to instance 0x5673650'

我正在尝试的事情是不可能的吗?感谢您的帮助...

【问题讨论】:

    标签: iphone uibutton


    【解决方案1】:

    您可能只使用UIButtontag 属性来存储您的节号(可能带有偏移量,因为tag 默认为0)

    【讨论】:

    • 是的,这会起作用 - 不知道为什么我没有想到这一点。会告诉你进展如何!
    • 完美运行。很简单。也感谢其他人的选择。
    • @MattFacer 如果我已经将标签用于其他用途,是否还有其他属性可以使用/或者我需要制作自定义 uibutton 来执行此操作
    【解决方案2】:

    这是不可能的,因为您正在使用函数调用:

    [MattsButtonClass buttonWithType:UIButtonTypeCustom]
    

    该消息将返回一个 UIButton而不是一个 MattsButtonClass。这就是返回的对象上不存在该属性的原因。这使得 UIButton 的子类化变得困难。但是,您可以通过以下方式实现您想要的功能:

    MattsButtonClass *button = [[MattsButtonClass alloc] initWithFrame:CGRectMake(240, 15, 45, 30)];
    button.MFsectionNo = section;
    

    【讨论】:

      【解决方案3】:

      也许保留一个数组,其中包含对每个部分标题中按钮的引用?

      -(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIButton *myButton = [[UIButton alloc] init]; [myButton addTarget:self action:@selector(myButton_touchUpInside:) forControlEvents:UIControlEventTouchUpInside]; // 之前定义为视图控制器的实例变量 // NSMutableArray *sectionHeaderButtons; [sectionHeaderButtons insertObject:myButton atIndex:section]; }

      然后在按钮的TouchUpInside事件的处理程序中:

      - (void)myButton_touchUpInside:(id)sender { 诠释我; for (i = 0; i

      如果触摸按钮的部分索引是您所追求的,那么这应该可以解决问题。但是,如果出现以下情况,则不是最佳选择:

      1. 您正在重新排列 TableView 部分,或者
      2. 你有很多部分

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多