首页 > 解决方案 > 如何根据swift4中的视图内容使视图高度为0

问题描述

我是 iOS 新手。我将拥有一系列产品。每个产品将具有该产品的最小 0 到最大 15 个详细信息。每当我们单击一个产品时,该产品的相关详细信息应显示在其他视图控制器中。如果该产品有 5 个详细信息,则应仅显示 5 个详细信息。其余详细信息字段高度应变为 0。这是我的要求。我试过这个,但我正在处理类似“线程 1:信号 SIGABRT”的错误。在控制台中“可以未将“NSNull”(0x107e57de0)类型的值转换为“NSString”(0x106ef25d8)。2019-02-15 11:28:51.808090+0530 PlanetZoomApp [6777:85237] 无法将“NSNull”(0x107e57de0)类型的值转换为'NSString' (0x106ef25d8)。” 如果有人帮助我,那就太好了。提前致谢。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let lmp = storyboard.instantiateViewController(withIdentifier: "LocatemypicViewController") as!  


 if let desc:String = (dictobj["description"] as! String){

            print(desc)

            lmp.des = desc
        }else{
            lmp.descriptionviewheight.constant=0
        }

self.navigationController?.pushViewController(lmp, animated: true)

    }

标签: iosswift4

解决方案


当你使用 if let 时,你通常不应该使用强制转换 as!,第二个问题是在调用 viewDidLoad 之前没有初始化约束。因此您可以将值保存在某处并在内部 LocatemypicViewController viewDidLoad 上使用它。

总的来说,我建议你将 dictobj["description"] 传递给下一个视图控制器,并在 viewDidLoad 中执行逻辑,并避免在父视图控制器上执行另一个视图的逻辑。

class ViewController1:UIViewController {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let lmp = storyboard.instantiateViewController(withIdentifier: "LocatemypicViewController") as!  


        if let desc:String = (dictobj["description"] as? String){

            print(desc)

            lmp.des = desc
        }else{
            lmp._descriptionviewheight = 0
        }

        self.navigationController?.pushViewController(lmp, animated: true)

    }
}

class LocatemypicViewController:UIViewController {
   var _descriptionviewheight = 0

   override func viewDidLoad() {
      descriptionviewheight.constant = _descriptionviewheight
   }

}

推荐阅读