簡體   English   中英

iOS無法設置UIButton的backgroundImage

[英]iOS can't set backgroundImage of UIButton

我似乎無法讓系統使用我擁有的自定義創建按鈕。 我在.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;
}

當我運行應用程序時,按鈕是我在界面構建器中創建的默認白色按鈕。

在加載視圖之前調用init方法,因此useLocationButton尚不存在。

將您的視圖設置放在UIViewControllerviewDidLoad方法中,如下所示:

- (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實際連接。 您可能希望設置斷點以檢查引用是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM