【问题标题】:Using an URL image with an UIButton使用带有 UIButton 的 URL 图像
【发布时间】:2019-03-24 18:56:15
【问题描述】:

我正在尝试将 URL 图像设置为 swift 4 中的 UIButton。我正在使用 AFNetworking 从 url 加载我的图像。我正在查看将图像设置为按钮的最佳途径。

使用.setImage()setImageWith() 不适用于url 和uibuttons。

这是正在使用的 URL:

let imageUrl = URL(string: baseUrl + profile)

【问题讨论】:

标签: ios swift uibutton uiimage afnetworking


【解决方案1】:

我发帖是因为当前的答案建议使用另一个库 (SDWebImage),而 AFNetworking 已经为 UIButton 提供了扩展名 UIButton + AFNetworking.h(和 .m)。

声明在 Objective-C 中,但您应该能够在代码中使用 Swift 等效的声明:

- (void)setImageForState:(UIControlState)state
                 withURL:(NSURL *)url;
- (void)setImageForState:(UIControlState)state
                 withURL:(NSURL *)url
        placeholderImage:(nullable UIImage *)placeholderImage;
- (void)setImageForState:(UIControlState)state
          withURLRequest:(NSURLRequest *)urlRequest
        placeholderImage:(nullable UIImage *)placeholderImage
                 success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
                 failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;

backgroundImage 也有相同的版本。

【讨论】:

    【解决方案2】:

    您可以使用SDWebImage,它也有UIButton 的类别/扩展名

    btn.sd_setImage(with:URL(string: "Your_url"), forState:.normal)
    

    【讨论】:

    • 我正在尝试这个 cell.bProfileImage.sd_setImage(with:URL(string: individualChatsListArray[indexPath.row].profile_image), forState:.normal) 但得到可选类型 'UIButton?' 的错误值必须解包以引用已封装基类型“UIButton”的成员“sd_setImage”
    • cell.bProfileImage!.替换cell.bProfileImage.
    • 但是,如果我使用的是 kingfisher 库?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多