开发者

How to programmatically set the background on a UICustomButton?

开发者 https://www.devze.com 2023-04-11 00:36 出处:网络
I know this question has been asked and answered in other forums, but I can\'t seem to duplicate what they did and get it to work. I am trying to set the background to a button using a picture that I

I know this question has been asked and answered in other forums, but I can't seem to duplicate what they did and get it to work. I am trying to set the background to a button using a picture that I download from a server. Everything works until I try to make a NSData object with the contents of a URL. When I try and print the Data to the screen it comes back Null. What am I doing wrong?

myImageURLString = [[NSMutableString alloc] initWithString:@"http://destinationnexus.com"];
    keyName = [businessButtonTagArray objectAtIndex:i];
    arrayFromBusinessDictionary = [businessDictionary objectForKey:keyName];
    stringToAddToMyImageURLString = [arrayFromBusinessDictionary objectAtIndex:1];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [button setTag:i];  
    button.frame = CGRectMake(xOffSet+(countForX*xMult), yOffset +(countForY*yMult), 215, 155);

    [myImageURLString appendString:stringToAddToMyImageURLString];
    NSLog(@"Appended URL String: = %@", myImageURLString);


    NSURL *myImageURL = [NSURL URLWithString:@"http://destinationnexus.com/pictures/direc开发者_运维技巧tory/ColdWater-Inn-in-Tuscumbia-Alabama-35674-8729//.jpg"];
    NSLog(@"NSURL = %@", myImageURL);
    //THIS IS WHERE I SEEM TO HAVE A PROBLEM.....
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:myImageURL];
    UIImage *image = [[UIImage alloc] initWithData:imageData] ;
    NSLog(@"Image Data = %@", imageData);
    //UIImage *myImage = [UIImage imageWithData:imageData] ; 
    [button setBackgroundImage:image forState:UIControlStateNormal];

When I run the program this is what it outputs in the Log:

Appended URL String: = http://destinationnexus.com/pictures/directory/Auburn-University-Hotel-and-Center-in-Auburn-Alabama-36830-5429.jpg

NSURL = http://destinationnexus.com/pictures/directory/ColdWater-Inn-in-Tuscumbia-Alabama-35674-8729.jpg

Image Data = (null)


You should correct your myImageURL, by deleting 2 slashes at the end of URL.

The code goes something like this.

NSURL *myImageURL = [NSURL URLWithString:@"http://destinationnexus.com/pictures/directory/ColdWater-Inn-in-Tuscumbia-Alabama-35674-8729.jpg"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:myImageURL];
UIImage *image = [[UIImage alloc] initWithData:imageData] ;
[button setBackgroundImage:image forState:UIControlStateNormal];
[image release];
[imageData release];
0

精彩评论

暂无评论...
验证码 换一张
取 消