ios - 从互联网下载图像后将图像设置为 UIlabel

标签 ios swift swift3

我希望你能帮我解决这个问题。

我正在尝试从 url 下载图像并将其设置为标签。我可以在 imageView 中显示它,但不能在标签中显示。

这是我的代码。

func updateImage() {

    let ref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    let usersRef = ref.child("users").child(uid!)

    // only need to fetch once so use single event

       Database.database().reference().child("Products").queryOrderedByKey().observe(.childAdded, with: { snapshot in

        if !snapshot.exists() { return }

        //print(snapshot)

        let userInfo = snapshot.value as! NSDictionary
        print(userInfo)
        print(userInfo["name"]!)
        let profileUrl = userInfo["photoURL"] as! String

        print(profileUrl)
        let storageRef = Storage.storage().reference(forURL: profileUrl)
        storageRef.downloadURL(completion: { (url, error) in
            do {
                let data = try Data(contentsOf: url!)
                let image = UIImage(data: data as Data)
                self.productPhoto.image = image

            }
            catch _ {
                // Error handling
            }

        })
    })
}

我试过很多这样的事情

self.swipeLabel.backgroundColor = UIColor(patternImage: UIImage(named: image))

提前致谢

最佳答案

试试这个,因为我认为你正在尝试做的是将背景图像设置为 UILabel。 假设您从数据中获得图像:

let data = try Data(contentsOf: url!)
let image = UIImage(data: data as Data)

现在您可以使用属性字符串将此图像设置为带有文本的 UILabel,如下所示:

 let imageAttachment =  NSTextAttachment()
    imageAttachment.image = image
    //Set bound to reposition
    let imageOffsetY:CGFloat = -5.0;
    imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: imageAttachment.image!.size.width, height: imageAttachment.image!.size.height)
    //Create string with attachment
    let attachmentString = NSAttributedString(attachment: imageAttachment)
    //Initialize mutable string
    let completeText = NSMutableAttributedString(string: "")
    //Add image to mutable string
    completeText.append(attachmentString)
    //Add your text to mutable string
    let  textAfterIcon = NSMutableAttributedString(string: "Using attachment.bounds!")
    completeText.append(textAfterIcon)
    self.label.textAlignment = .center;
    self.label.attributedText = completeText;

或者如果你想将图像设置为背景,那么你可以尝试将 ImageView 添加为 UILabel 的 subview ,反之亦然,如下所示:

label.addSubview(imageView)imageView.addSubview(label)

您也可以尝试将图像直接设置为 UILabel 的背景:

label.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)

关于ios - 从互联网下载图像后将图像设置为 UIlabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47170415/

相关文章:

ios - 用于构建需要来自多个 UIViewController 的数据的对象的设计模式

ios - Devise with Facebook Omniauth - 如何使用 API 进行身份验证?

ios - 我怎样才能 'add' 两个NSLayoutDimension?

iOS 在自定义类中处理 didSelectRowAtIndexPath

快速浏览字典

ios - Swift - 检查对象是否属于给定类型(类型已作为函数参数传递)

ios - 我必须使用标准的共享 UserDefaults 对象吗?

ios - Realm swift : instance member cannot be used on type

ios - ARKit 将模型随机放置在现实世界中

ios - Google map 无法缩放到我当前的位置