Swift 如何将 UIStackView 放置在 ImageView 的特定角落

Swift How to Place UIStackView in a Specific Corner of ImageView

所以基本上我有一个 ImageView 和一个 HorizontalStackView (the one circled in red) 。用户单击按钮后,我试图在图片的右上角覆盖堆栈视图布局。不用说,我无法控制加载到 ImageView 中的图片,因为它是从互联网上获取的。我在 Apple 文档上读到 .contentMode 会得到我正在寻找的结果。因此,这是我的代码示例

 case .UpRight:
        repostLayout.contentMode = .topRight
        imageView.addSubview(repostLayout)

如您所料,运行 应用程序没有任何变化。有人能给我指出正确的方向吗?

提前致谢...

如果我理解您要实现的目标,为什么不让包装 UIView 包含图像和 stackView 作为子视图,并简单地将图像限制在视图的尺寸范围内,并将 stackview 限制在右上角?

举个例子:

class MyViewController: UIViewController {
    let wrapperView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    //Your existing stack
    private let stackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        return stack
    }()
    
    //Your existing imageView
    private let imageView: UIImageView = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //Shouldn't necessarily be in viewDidLoad, but just for example:
        view.addSubview(wrapperView)
        //Set wrapperView's constraints to where the image currently is
        
        imageView.translatesAutoresizingMaskIntoConstraints = false
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        wrapperView.addSubview(imageView)
        wrapperView.addSubview(stackView)
        imageView
            .topAnchor
            .constraint(equalTo: wrapperView.topAnchor)
            .isActive = true
        imageView
            .bottomAnchor
            .constraint(equalTo: wrapperView.bottomAnchor)
            .isActive = true
        imageView
            .leadingAnchor
            .constraint(equalTo: wrapperView.leadingAnchor)
            .isActive = true
        imageView
            .trailingAnchor
            .constraint(equalTo: wrapperView.trailingAnchor)
            .isActive = true
        
        stackView
            .topAnchor
            .constraint(equalTo: wrapperView.topAnchor)
            .isActive = true
        stackView
            .trailingAnchor
            .constraint(equalTo: wrapperView.trailingAnchor)
            .isActive = true
        
        //Make sure your stack view is not too wide or too tall for the wrapper
        //Either by using constraints or by any other method.
    }
}

通过故事板可以轻松实现同样的效果。如果你遇到困难,我会 post 故事板也一样。