如何在另一个视图中约束UIImageView?

时间:2016-01-01 21:20:13

标签: ios swift autolayout core-graphics ios-universal-app

我在xcode中有一个通用的iOS swift项目,但我无法获得UIImageView的大小。 XIB结构如下:

View |-- Card (View) |-- CoverImage (UIImageView)

ViewUIScrollView加载到ViewController.swiftCard设置了top,bottom,trailing和leading约束,以便有20px'的边距。周围。 Card也有圆角。 CoverImage具有类似的约束,其中top,trailing和leading设置为superview,bottom在viewDidLoad()中定义为Card高度的40%。问题是CoverImage的宽度超过Card的宽度,超出部分未显示。因此,当我尝试围绕CoverImage的顶角时,只有左上角是圆角的。

leadingConstraint.constanttrailingConstraint.constant设置为0似乎没有任何效果,因为右上角仍然没有停止。

如何正确设置CoverImage的约束以使其大小正确?这是我在XIB中设置的约束的问题,还是有更好的方法来定义子视图的大小?

作为参考,这是包含CardCoverImage的视图的控制器swift文件:

class CardViewController: UIViewController {

// MARK: Connect All Subviews/Objects
@IBOutlet weak var card: UIView!
@IBOutlet weak var coverImage: UIImageView!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var trailingConstraint: NSLayoutConstraint!
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    // MARK: Draw Card
    card.layer.cornerRadius = 2
    card.layer.shadowRadius = 3
    card.layer.shadowOpacity = 0.15;
    card.layer.shadowOffset = CGSizeMake(1, 1)
    card.backgroundColor = UIColor.whiteColor()

    // MARK: Draw Cover Image
    let imageViewShape : CAShapeLayer = CAShapeLayer()
    imageViewShape.bounds = coverImage.frame
    imageViewShape.position = coverImage.center
    imageViewShape.path = UIBezierPath(roundedRect: coverImage.bounds, byRoundingCorners: [UIRectCorner.TopRight, UIRectCorner.TopLeft], cornerRadii: CGSize(width: 2, height: 2)).CGPath
    coverImage.layer.mask = imageViewShape
    bottomConstraint.constant = card.frame.height * 0.4

}
}

感谢任何可以提供帮助的人!

1 个答案:

答案 0 :(得分:1)

首先,如果您尝试在viewDidLoad上设置CAShapeLayer的范围,您将获得不正确的尺寸,因为目前尚未在设备上呈现超级视图;它应该在viewDidAppear上创建。

现在我们有了正确的框架,我们必须在superview中正确定位它,默认情况下,我们附加的蒙版继承了它应用的视图的约束,因此我们必须调整它的原点在两个轴上都有20个像素。

我以前使用的代码看起来很好,因为你要求它:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let imageViewShape : CAShapeLayer = CAShapeLayer()
    imageViewShape.frame = coverImage.frame
    imageViewShape.bounds = CGRect(origin: CGPoint(x: coverImage.bounds.origin.x + 20, y: coverImage.bounds.origin.y + 20), size: coverImage.bounds.size)
    imageViewShape.path = UIBezierPath(roundedRect: coverImage.bounds, byRoundingCorners: [UIRectCorner.TopRight, UIRectCorner.TopLeft, UIRectCorner.BottomLeft, UIRectCorner.BottomRight], cornerRadii: CGSize(width: 10, height: 10)).CGPath
    coverImage.layer.mask = imageViewShape

}