【发布时间】:2013-10-14 05:05:24
【问题描述】:
首先,我是 Objective-C 的新手。 在我的应用程序中,我想创建一个按钮列表,其中背景图像设置为我在 Facebook 上朋友的个人资料图片。为此,我打算使用个人资料图片的 url 作为按钮的背景图片。这甚至可能吗,还是我必须先下载图像内容,将其保存在本地设备上,然后再使用?
最直接的方法是什么?
提前致谢!
T
【问题讨论】:
标签: ios objective-c cocoa-touch
首先,我是 Objective-C 的新手。 在我的应用程序中,我想创建一个按钮列表,其中背景图像设置为我在 Facebook 上朋友的个人资料图片。为此,我打算使用个人资料图片的 url 作为按钮的背景图片。这甚至可能吗,还是我必须先下载图像内容,将其保存在本地设备上,然后再使用?
最直接的方法是什么?
提前致谢!
T
【问题讨论】:
标签: ios objective-c cocoa-touch
作为 Joel said,您可以使用 FBProfilePictureView 获取图像。如果你不想使用 Facebook API,你可以使用这个非常(太)简单的方法,只是为了了解机制:
// Creation of an UIImageView (which will be used as the button's background)
UIImageView *imageView = [[UIImageView alloc] init];
// Fetch the image data from a specific URL
NSString *imageURL = @"yourProfilePictureURL";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
// Assign the image data we fetched to the UIImageView
imageView.image = [UIImage imageWithData:imageData];
// Creation of the UIButton (if you didn't do this in your story board)
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
// Set the background image of the button with the image you fetched before
[button setBackgroundImage:imageView.image forState:UIControlStateNormal];
// Add the button to the view (useless if you used storyboard)
[self.view addSubview:button];
正如我所说,这种方法非常简单、易懂且易于使用,但我建议您改用 Facebook API(这需要更多的工作)。请参阅 FBProfilePictureViewdocumentation、here 和 here,了解有关本课程的已问问题。
【讨论】:
dataWithContentsOfURL 是同步的并且会阻塞主线程(no es bueno),所以你需要在后台线程上运行它。这可能超出了 OP 的能力。
您可以使用 Facebook iOS SDK 中的 FBProfilePictureView 来显示个人资料图片。提供文档here。我敢肯定,如果您搜索FBProfilePictureView,您也可以找到示例代码。
【讨论】: