【问题标题】:Create iOS image button with URL source in Objective C [closed]在Objective C中使用URL源创建iOS图像按钮[关闭]
【发布时间】:2013-10-14 05:05:24
【问题描述】:

首先,我是 Objective-C 的新手。 在我的应用程序中,我想创建一个按钮列表,其中背景图像设置为我在 Facebook 上朋友的个人资料图片。为此,我打算使用个人资料图片的 url 作为按钮的背景图片。这甚至可能吗,还是我必须先下载图像内容,将其保存在本地设备上,然后再使用?

最直接的方法是什么?

提前致谢!

T

【问题讨论】:

    标签: ios objective-c cocoa-touch


    【解决方案1】:

    作为 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(这需要更多的工作)。请参阅 FBProfilePictureViewdocumentationherehere,了解有关本课程的已问问题。

    【讨论】:

    • 这种方法的问题是dataWithContentsOfURL 是同步的并且会阻塞主线程(no es bueno),所以你需要在后台线程上运行它。这可能超出了 OP 的能力。
    • 如果您想避免使用 Facebook SDK 并仅从 URL 加载它,我可能会使用 UIImageView+AFNetworking 类别扩展,因此您不必担心从头开始编写异步图像加载。
    • 是的,我完全理解这一点,我给出的解决方案简单明了。使用 UIImageView+AFNetworking 类别是个好主意,我同意!
    • 各位,非常感谢你们的回答。当乔尔首先用 FBProfilePictureView 的建议做出回应时,我在谁来授予“答案”之间左右为难,这可能是解决我需要做的事情的最佳方式。但随后 Arnaud 的回答正是我所要求的,即创建一个 UIIMage 对象并将其设置为按钮的背景图像(以及一个非常全面的示例代码截图)。然而,我将答案授予 Joel 只是因为这是我可能实施的解决方案。谢谢大家。
    【解决方案2】:

    您可以使用 Facebook iOS SDK 中的 FBProfilePictureView 来显示个人资料图片。提供文档here。我敢肯定,如果您搜索FBProfilePictureView,您也可以找到示例代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      相关资源
      最近更新 更多