我有一个视图控制器,我有一个UIImage和UIlabels。此UIimage - 从服务器加载图像,UIlabel文本从数据库中定义的字段中获取值。现在,在一些记录中,我们在服务器上没有图像并且是空白的,但总会有UILabel值。因此,如果我们没有图像价值,我们如何删除UIImage并带上标签(如屏幕截图所示)。
在第一个截图中,我们有图像,所以很好,但第二个截图我们只有文字,并希望带来文本。有一个简单的方法吗?
另外,如果我们在高度和宽度方面有各种尺寸的图像,那么我们如何从服务器获取应用程序上加载的图像的实际尺寸
代码:
private func checkImage(_ imageString:String)
{
self.imageUI.layoutIfNeeded()
if imageString.characters.count >= 2
{
if imageString != "<null>"
{
let url = NSURL(string:"http://www.xyz.com.au/images/"+imageString)
let data = NSData(contentsOf:url! as URL)
if data != nil
{
imageUI.image = UIImage(data:data! as Data) //= UIImage(data:data!)
//imageUI.sizeToFit()
let data = NSData(contentsOf: url as! URL)
let Image = UIImage(data: data as! Data)!
DispatchQueue.main.async {
if data != nil
{
// We've received valid image.
// Find the height & Width of received image and update the image-view's height constraint.
imageUI.image = data!.size.height
}
else
{
// Sorry,The received image is invalid,Need to hide Image View,So make the Image-view height constraint's constant to 0 which eventually hides it self and pulls that below label up!
imageUI.constraints = 0
}
}
}
}
else
{
//logoImageView.image = UIImage(named: "error-404")
}
}
else
{
//logoImageView.image = UIImage(named: "error-404")
}
}
答案 0 :(得分:1)
你可以给它高度约束并将其设置为0(所需优先级,先禁用它,在需要时再次启用)如果图像/标签为零,请记住使其他相关约束更低优先级
答案 1 :(得分:1)
Try this,
// 1. Get a reference to your image view's height constraint from story board to View controller.
// Assume "constraintImageViewHeight" is the object name of the IBOutlet of image view's height constraint.
// 2. In Web service completion block,Check for received image is nil/null
// Assume "imgRecieved" is the object name of UIImage converted from response received.
DispatchQueue.main.async {
if imgRecieved != nil
{
// We've received valid image.
// Find the height & Width of received image and update the image-view's height constraint.
constraintImageViewHeight.constant = imgRecieved!.size.height
}
else
{
// Sorry,The received image is invalid,Need to hide Image View,So make the Image-view height constraint's constant to 0 which eventually hides it self and pulls that below label up!
constraintImageViewHeight.constant = 0
}
}
Check this out for more information.
Hope that helps!