addArrangedSubview vs addSubview

Mah*_*asi 9 xcode ios swift uistackview

I'm newbie and I've wrote a customView inherited from StackView and I created a button programmatically with few attributes and when I add it to my custom view, I have two problems:

  1. If I use addArrangedSubview(myBtn), my view ignores attributes that I added and fills the whole width. But if I use addSubView(myBtn), It's ok(a blue square in 44x44)
  2. If I use addArrangedSubview(myBtn), addTarget() not works and myBtn is not clickable, but when I use addSubView(myBtn), It works perfectly.

Here is my custom view class:

import UIKit

class RatingControl: UIStackView {

//MARK: Initialization
override init(frame: CGRect) {
    super.init(frame: frame)
    setupButtons()
}

required init(coder: NSCoder) {
    super.init(coder:coder)
    setupButtons()
}

//MARK: Private Methods
private func setupButtons() {

    // Create the button
    let button = UIButton()
    button.backgroundColor = UIColor.blue

    // Add constraints
    button.translatesAutoresizingMaskIntoConstraints = false
    button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
    button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true

    // Setup the button action
    button.addTarget(self, action: #selector(ratingButtonTapped(_:)), for: .touchUpInside)

    // Add the button to the stack
    addArrangedSubview(button)

}
//MARK: Button Action
@objc func ratingButtonTapped(_ sender: Any) {
    print("Button pressed ")
}

}
Run Code Online (Sandbox Code Playgroud)

Here is the preview:

在此处输入图片说明 在此处输入图片说明

What's difference between addSubView() and addArrangedSubview()? why these problems happens?

Don*_*Mag 8

我假设您想水平添加几个按钮(例如使用典型的“星级”评级控件)。

UIStackView,因为可能从它的猜测.addArrangedSubview()方法,安排其子视图,基于其.axis.alignment.distribution.spacing性质,以及它frame

因此,请阅读有关UIStackView以及如何使用它的一些信息。最有可能的是,您目前正在通过以下方式限制您的自定义视图:

  • 最佳
  • 领导
  • 尾随(或宽度)

所以添加你的按钮会arrangedSubView导致它拉伸到堆栈视图的宽度,因为这是默认值。

添加它作为subview简单地覆盖堆栈视图上的按钮,而不是允许堆栈视图排列它,并且您的堆栈视图可能具有零高度 - 因此无法点击按钮。

添加自定义堆栈视图时,请尝试设置顶部和前导约束。这应该会给你一个44 x 44可以点击的按钮。

当您使用 添加更多按钮时.addArrangedSubview(),这些按钮将水平排列,这可能正是您想要的。