xcode 如何显示来自 URL 的图像并在点击 UIButton 时显示它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8118151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:25:08  来源:igfitidea点击:

How to display image from an URL and display it on tap of a UIButton?

iphoneobjective-ciosxcode

提问by raptor85

I want to know how to display image from URL (which is in xml file) on tap of button.

我想知道如何通过点击按钮显示来自 URL(在 xml 文件中)的图像。

回答by Minakshi

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(20, 20, 200, 44); // position in the parent view and set the size of the button
[myButton setTitle:@"Click Me!" forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
// add to a view
[superView addSubview:myButton];

And function after tapping button

和点击按钮后的功能

-(void)buttonClicked{
    //urlString should be your image url which you want to access
    NSURL *url = [[NSURL alloc] initWithString:urlString ];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSData *urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}

Use image where you want to display.........

在要显示的地方使用图像........

回答by mandeep-dhiman

   UIImage *pImage=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];;
  [imageView setImage:pImage];