将按钮添加到堆栈视图完全占用父堆栈视图

Adding button to stack view entirely takes up of parent stack view

我一直在尝试将按钮添加到动态垂直堆栈视图中,堆栈视图位于水平堆栈视图中的滚动视图中。每当我向堆栈视图添加一个按钮时,它都会占据整个水平堆栈视图,这里是:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let button = UIButton()
        button.setTitle("test", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        Stack.addArrangedSubview(button)
        Stack.translatesAutoresizingMaskIntoConstraints = false
    }

完整代码:

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var emotionsStack: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let button = UIButton()
        button.setTitle("test", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = true
        button.frame.size = CGSize(width: emotionsStack.frame.width, height: (emotionsStack.frame.width/10))
        emotionsStack.addArrangedSubview(button)
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches,
                           with: event)
        self.view.endEditing(true)
    }
    }


编辑:

发生的事情是堆栈视图接管了文本视图(红色)。这不应该发生。

因为 stackView 没有检测到尺寸,所以你必须给每个按钮一个固定尺寸的宽度或高度,这取决于 stackView 的类型“垂直或水平”,所以试着给你的按钮一个宽度,它会起作用。

-> 您可以使用 stackView 宽度或高度减去空格,然后除以按钮数,然后为每个按钮分配值

已编辑: 编辑我的答案后,如果您需要这样,我添加了一段代码和一张图片,如果不需要,请提供一张显示您想要的结果的图片:

import UIKit

class StackViewController: UIViewController {
    
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var emotionsStack: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        for i in 0...10 {
        let button = UIButton()
        button.setTitle("test \(i)", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = true
        button.frame.size = CGSize(width: emotionsStack.frame.width, height: ((emotionsStack.frame.width - 30 )/10))
        emotionsStack.addArrangedSubview(button)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches,
                           with: event)
        self.view.endEditing(true)
    }
}

结果: