我希望你能帮助我解决这个问题。
我正在尝试从网址下载图片并将其设置为标签。我能够在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))
提前谢谢
答案 0 :(得分:3)
尝试这个,因为我认为您要做的是将背景图像设置为UILabel
。
假设您已从数据中获取图像:
let data = try Data(contentsOf: url!)
let image = UIImage(data: data as Data)
现在,您可以使用Attributed字符串将此图像设置为带文本的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的子视图,反之亦然,如下所示:
label.addSubview(imageView)
或imageView.addSubview(label)
您也可以尝试将此图像直接设置为UILabel的背景:
label.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)