如何以编程方式设置UICustomButton的背景?

时间:2011-10-03 20:49:19

标签: iphone ios4 uibutton uiimage

我知道这个问题已经在其他论坛上被提出并得到了解答,但我似乎无法复制他们的所作所为并让它发挥作用。我正在尝试使用从服务器下载的图片将背景设置为按钮。一切正常,直到我尝试使用URL的内容创建NSData对象。当我尝试将数据打印到屏幕时,它返回Null。我究竟做错了什么?

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/directory/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];

当我运行程序时,这是它在Log中输出的内容:

附加网址字符串:= 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

图像数据=(null)

1 个答案:

答案 0 :(得分:3)

您应该通过删除网址末尾的2个斜杠来更正myImageURL。

代码就是这样的。

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];