0

我似乎无法让系统使用我拥有的自定义创建的按钮。我的 .m 文件的接口部分有以下声明:

@property (weak, nonatomic) IBOutlet UIButton *useLocationButton;
@property (weak, nonatomic) IBOutlet UIButton *useAddressButton;

然后我的init函数有以下内容

- (id)init
{
if (self = [super initWithNibName:@"TCMDirectionsViewController" bundle:nil]){

    [[self navigationItem] setTitle:@"Get Directions"];

    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                target:self
                                                                                action:@selector(cancel:)];
    click = NO;
    [[self navigationItem] setLeftBarButtonItem:cancelItem];

    UIImage *buttonImage = [[UIImage imageNamed:@"bluebutton.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
    UIImage *buttonImageHighlight = [[UIImage imageNamed:@"bluebuttonHighlight.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];

    [[self useLocationButton] setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [[self useLocationButton] setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
    [[self useAddressButton] setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [[self useAddressButton] setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
    _locationManager = [[CLLocationManager alloc] init];
    [_locationManager setDelegate:self];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    [_locationManager startUpdatingLocation];
}

return self;
}

当我运行应用程序时,虽然按钮是我在界面生成器中创建的默认白色按钮。

4

1 回答 1

2

init方法在视图加载之前被调用,所以useLocationButton还不存在。

将您的视图设置放在您的viewDidLoad方法中,UIViewController如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *buttonImage = [[UIImage imageNamed:@"bluebutton.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
    UIImage *buttonImageHighlight = [[UIImage imageNamed:@"bluebuttonHighlight.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];

    [[self useLocationButton] setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [[self useLocationButton] setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
    [[self useAddressButton] setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [[self useAddressButton] setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
}

另外,请确保您IBOutlets已实际连接。您可能需要设置断点来检查引用是否有效。

于 2013-08-08T14:50:59.347 回答