【问题标题】:Setting up a subclass for UIButton to handle look-and-feel为 UIButton 设置一个子类来处理外观
【发布时间】:2013-08-29 04:40:41
【问题描述】:

我有一个 AuthButtons.h 标头:

#import <UIKit/UIKit.h>

@interface AuthButtons : UIButton

@property (nonatomic, weak) UIColor *backgroundColor;


@end

实现AuthButtons.m类如下:

#import "AuthButtons.h"

@implementation AuthButtons

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    backgroundColor = [UIColor blueColor];
}

- (UIColor *)backgroundColor
{
    return [UIColor whiteColor];
}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

然后在我的 viewcontroller.m 类中我有:

@interface ViewController ()

@property (nonatomic, weak) AuthButtons *registerButton;


@end


...

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _registerButton = [AuthButtons buttonWithType:UIButtonTypeSystem];
    [_registerButton setTitle:@"Register" forState:UIControlStateNormal];
    [_registerButton setBackgroundColor:[UIColor whiteColor]];
    _registerButton.frame = CGRectMake(0.0, 0.0, self.screenWidth / 2.0, 100.0);

    [_registerButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}

当我尝试创建按钮时,它一直在崩溃。我错过了什么?

【问题讨论】:

    标签: iphone ios objective-c ios6


    【解决方案1】:

    你的按钮很弱,没有添加为子视图,所以它立即被释放

    【讨论】:

      【解决方案2】:

      使用强而不是弱(在启用 ARC 的类中使用按钮时我总是使用强类型,不确定它是否是一个坏习惯 :-))

      @property (nonatomic, strong) AuthButtons *registerButton;
      

      并将其添加为您的子视图([self.view addSubview:_registerButton])。希望您已在课堂上实现了名为-(void)buttonPressed:(id )sender 的函数。

      【讨论】:

      • 仍然在那条线上崩溃,肯定有其他事情发生
      • nm,我有一个放错位置的 [ 在评论之外
      • 你从哪里得到 buttonWithType:UIButtonTypeSystem?..它必须是 buttonWithType:UIButtonTypeCustom..
      • 如何使用 backgroundColor 从 AuthButtons 类设置我的按钮背景颜色?
      • -(void)setUrBackgroundColor:(UIColor *)urcolor;将此添加到您的 AuthButtons.h 并实现 -(void)setUrBackgroundColor:(UIColor *)urcolor { self.backgroundColor=urcolor; } 在你的 AuthButtons.m 类中
      猜你喜欢
      • 2012-08-23
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 2015-07-03
      • 2012-05-03
      • 2011-08-19
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多