约束按钮到UIImageView内的图像

问题描述 投票:0回答:1

我有一个UIImageView,用户可以设置图像,以便width/height变化。我想在右上角添加“ x”-button,但不是从UIImageView,而是从实际的image

这里是现在的样子。整个图片是UIImageView,在左侧可以看到image,在右上角可以看到button

enter image description here

这是我目前的约束方式:

deleteImageButton.widthAnchor.constraint(equalToConstant: 10).isActive = true
deleteImageButton.heightAnchor.constraint(equalToConstant: 10).isActive = true
deleteImageButton.topAnchor.constraint(equalTo: wishImageView.topAnchor, constant: 5).isActive = true
deleteImageButton.trailingAnchor.constraint(equalTo: wishImageView.trailingAnchor, constant: -5).isActive = true

这显然是错误的,但是有没有办法将其限制为实际的image

ios swift uiimageview uiimage
1个回答
0
投票

您的图像宽度到位置按钮。粗略了解并简化用户界面]

let imgWidth = iv.image?.size.width

NSLayoutConstraint.activate([
    iv.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    iv.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    iv.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    iv.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),

    btn.widthAnchor.constraint(equalToConstant: 20),
    btn.heightAnchor.constraint(equalToConstant: 20),
    btn.leadingAnchor.constraint(equalTo: iv.leadingAnchor , constant: imgWidth ?? 0),
    btn.topAnchor.constraint(equalTo: iv.topAnchor,constant: 10)

])

当图像宽度大于您的图像视图时会发生此问题。请对其进行验证以获得更好的结果。

Result

© www.soinside.com 2019 - 2024. All rights reserved.