【问题标题】:iOS contraints to center an image is not working将图像居中的 iOS 约束不起作用
【发布时间】:2016-04-08 17:31:13
【问题描述】:

我添加了 2 个约束以使 UIImageView 在 UIView 中居中。 约束是使其垂直和水平居中。 但由于某种原因,它没有居中。

请注意,容器 UIView 具有上、下、左、右的边距约束。

为什么居中不起作用? UIImageView 本身是否可能需要明确的大小?

很遗憾,这一切都是通过 Storyboard 完成的,所以我没有可以分享的 sn-ps。

【问题讨论】:

  • 要么给出水平和垂直约束,要么给出顶部和底部。不要两个都给。你可以分享你的故事板的图片,以及解释问题的图片。
  • 请记住,图像不一定在其图像视图中居中。给图像视图一个彩色背景并运行你的应用程序,这样你就可以看到图像视图的真正位置。您可能想向我们展示正在发生的事情的屏幕截图。

标签: ios autolayout


【解决方案1】:

您可以分享屏幕截图,例如需要哪种类型的布局。

您可以像这样将图像视图设置为水平和垂直。查看下图,

【讨论】:

    【解决方案2】:

    你可以试试下面的代码,它工作正常。

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let myImageView = UIImageView()
        myImageView.backgroundColor = UIColor.redColor()
        self.view.addSubview(myImageView)
        myImageView.translatesAutoresizingMaskIntoConstraints = false
        // set contentMode to center image
        myImageView.contentMode = .Center
    
        // if you want some specific heigh and width of myImageView then uncomment below Two line to add the height & Width constraints.
        // view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))
        // view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))
    
        // if you do not set the height and width constrints then myImageView size depends on actual size of image.
        view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多