【问题标题】:Reload View Controller and programatically change UIImageView constraint重新加载视图控制器并以编程方式更改 UIImageView 约束
【发布时间】:2016-04-22 10:17:31
【问题描述】:

我有一个 UIImageView,它的高度受用户从他们的库中拍摄或选择的照片的纵横比影响。在用户选择照片后,我无法让 UIImageView 适当地(或根本不)调整大小。

代码:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //let mediaType2 : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        let mediaType : CFString = info[UIImagePickerControllerMediaType] as! CFString

        if mediaType == kUTTypeMovie {
            let path = (info[UIImagePickerControllerMediaURL] as! NSURL).path
            if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path!) {
                UISaveVideoAtPathToSavedPhotosAlbum(path!, self, "video:didFinishSavingWithError:contextInfo:", nil)
            }
        }
        else{
            let img : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            let screenSize: CGRect = UIScreen.mainScreen().bounds
            let multiplyNum = screenSize.width / img.size.width
            imageView.frame = CGRectMake(0, 0, screenSize.width, multiplyNum*img.size.height)
            imageView.image = img

        }

        self.dismissViewControllerAnimated(true, completion: {})

    }

目前在情节提要中设置了约束,但我想以编程方式覆盖 imageView 的约束。

【问题讨论】:

    标签: ios swift uiimageview aspect-ratio


    【解决方案1】:

    您应该更新 UIImageView 的约束而不是设置框架。为图像视图设置一个高度约束,然后为该约束创建一个 IBOutlet(控制从约束拖动到它的视图控制器),将其称为“imageViewHeightConstraint”。然后在你的代码中说:

    imageViewHeightConstraint.constant = multiplyNum*img.size.height
    

    【讨论】:

      【解决方案2】:

      @beyowulf 的回答会奏效,而且很容易实现

      但是如果不想设置约束出口,可以在代码中指定 ratio 属性,witch 也很简单:

      //remove the last image ration constraint
      if let ratioConstrain = self.ratioConstrain {
          self.imageView.removeConstraint(ratioConstraint)
      }
      
      self.ratioConstraint = NSLayoutConstraint(
          item: self.imageView, attribute: NSLayoutAttribute.Width,
          relatedBy: NSLayoutRelation.Equal,
          toItem: self.imageView, 
          attribute: NSLayoutAttribute.Height,
          multiplier: image!.size.width / image!.size.height, 
          constant: 0)
      
      self.imageView.addConstraint(self.ratioConstraint!)
      

      不要使用不起作用的用户框架 在这种情况下,你需要去掉你的imageView的高度约束,并设置宽度等于超级视图,你会得到你想要的:屏幕宽度相等,高度随图片本身的比例变化。

      有一个问题,如果你从roll中得到的图像太小,你可能希望宽度小于屏幕,在这种情况下你应该将imageView的宽度约束设置为lessThanOrEqual(

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-18
        • 1970-01-01
        • 2014-12-18
        相关资源
        最近更新 更多