动态UIView大小

时间:2015-12-11 01:01:54

标签: ios swift uiview uiimageview autolayout

我遇到的问题是UIView以某种方式获得了不合需要的填充。似乎UIView框架根据UIImage高度调整自身大小。

These are my constraints on the UIView

Illustrative GIF

小区配置:

// Configure the cell...
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.testView.frame.width, height: cell.testView.frame.height))

    imageView.image = UIImage(named: "eiffel.JPG")
    imageView.autoresizingMask = .FlexibleWidth
    imageView.contentMode = .ScaleAspectFit
    imageView.center = cell.testView.center
    imageView.clipsToBounds = true
    imageView.translatesAutoresizingMaskIntoConstraints = false


    cell.testView.addSubview(imageView)

    let bottomMarginConstraint = NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: cell.testView, attribute: .Bottom, multiplier: 1, constant: 0)

    let topMarginConstraint = NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: cell.testView, attribute: .Top, multiplier: 1, constant: 0)

    let trailingMarginConstraint = NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: cell.testView, attribute: .Left, multiplier: 1, constant: 0)

    let leadingMarginConstraint = NSLayoutConstraint(item: imageView, attribute: .Right, relatedBy: .Equal, toItem: cell.testView, attribute: .Right, multiplier: 1, constant: 0)

    //let widthConstraint = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: imageView.superview!.frame.width)

    let constraints = [bottomMarginConstraint, topMarginConstraint, leadingMarginConstraint, trailingMarginConstraint]

    cell.testView.addConstraints(constraints)

UIView是具有浅绿色背景的单元,而单元格是具有粉红色背景的单元。

3 个答案:

答案 0 :(得分:1)

这可能是由于使用自动布局时默认添加的边距。 从故事板中取消选中它。

  • 取消选中"Constrain to margin"

Method 1

  • 取消选中"Relative To Margin"

Method 2

  • 尝试以编程方式删除

imageView.layoutMargins = UIEdgeInsetsMake(0, 0, 0,0);

查看更多: iOS8 Auto layout programatically pin to relative layout margin

Apple Doc Autolayout

答案 1 :(得分:0)

我认为你也可以在xib中绘制UIImageView。当UIImageView中的图像发生变化时,Auto layout的大小也会发生变化。您只需确认UIImageView的位置即可。

当tableView需要知道此单元格的高度时,返回cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).size.height + 1以计算Cell的contentView和1.f分隔线的高度

答案 2 :(得分:-2)

我最终做的是根据图像的宽度调整图像大小,然后根据重新计算的高度修改高度约束。