我希望你能帮我解决这个问题。
我正在尝试从 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/