1

我一直在尝试将矩形按钮的背景图像设置为我的网络服务器上的 .png 文件。我已经在视图控制器 .h 中声明了该按钮,并将其添加到 .m viewdidload 下:

[mybutton setImage: [UIImage imageNamed: @"http://www.myserver.com/index_files/stacks_image_14.png"] forState: UIControlStateHighlighted];

但按钮中没有显示任何内容。在尝试将图像分配给对象之前,我一直在阅读 NSSURL 以了解有关调用图像的信息,但目前我有点卡住了。

谢谢你的帮助!

编辑:我尝试过的新代码:

 NSURL *myurl2 = [NSURL URLWithString:@"http://www.myserver.com/bigoaks.png"];
    NSURLRequest *request2 = [NSURLRequest requestWithURL:myurl2
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:10.0];

    NSURLConnection *connection2= [[NSURLConnection alloc] initWithRequest:request2 
                                                                 delegate:self];
    NSString *mystring2 = [NSString stringWithContentsOfURL:myurl2 encoding:NSUTF8StringEncoding error:&error]; 
    [mybutton setImage : mystring2];

似乎仍然得到“UIButton 没有可见的@interface 声明选择器'setImage:'

再次感谢所有的帮助!

编辑2:

知道了!感谢所有帮助人员 - 这是帮助其他任何人的最终代码:

NSURL *myurl2 = [NSURL URLWithString:@"http://www.myserver.com/bigoaks.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:myurl2]];
[mybutton setImage:image forState:UIControlStateNormal];

使用本教程:http: //mobiledevelopertips.com/cocoa/download-and-create-an-image-from-a-url.html

4

3 回答 3

0
NSURL *url = [NSURL URLWithString:@"http://www.myserver.com/image.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[mybutton setImage:image];

希望这就是你要找的:)

于 2012-05-17T16:27:24.747 回答
0

imageNamed 用于使用捆绑包中包含的图像。另一个答案是正确的,尽管如果存在连接问题或一般延迟,该代码将冻结您的 UI,因为它不是异步的。相反,我建议使用 NSURLRequest 和 NSURLConnection 异步下载图像并将按钮设置为在完成委托函数(connectionDidFinishLoading)中使用它。

于 2012-05-17T16:46:45.507 回答
0

试试这个

[mybutton setBackgroundImage:[UIImage imageNamed:@"http://www.myserver.com/index_files/stacks_image_14.png"] forState:UIControlStateNormal];

于 2012-05-17T16:54:08.370 回答