简体   繁体   English

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

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

我想知道如何在点击按钮时从URL(在xml文件中)显示图像。

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......... 在要显示的位置使用图像.........

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM