addArrangedSubview vs addSubview

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

我是新手,我写了一个继承自StackView的customView,我用几个属性以编程方式创建了一个button,当我将它添加到我的自定义视图时,我有两个问题:

  1. 如果我使用addArrangedSubview(myBtn),我的视图会忽略我添加的属性并填充整个宽度。但如果我使用addSubView(myBtn),它没关系(44x44的蓝色方块)
  2. 如果我使用qazxsw poi,qazxsw poi不起作用且qazxsw poi不可点击,但当我使用addArrangedSubview(myBtn)时,它完美无缺。

这是我的自定义视图类:

addTarget()

这是预览:

myBtn addSubView(myBtn)

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 👍") } } enter image description here有什么区别?为什么会出现这些问题

ios swift xcode uistackview
1个回答
1
投票

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

一个enter image description here,可能从它的addSubView()方法猜测,根据其addArrangedSubview()UIStackView.addArrangedSubview().axis属性,以及它的.alignment安排其子视图。

所以,做一些关于.distribution及其如何使用的阅读。最有可能的是,您目前正在限制自定义视图:

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

因此,将您的按钮添加为.spacing会导致它延伸到堆栈视图的宽度,因为这是默认值。

将其添加为frame只需覆盖堆栈视图上的按钮,而不是允许堆栈视图排列它,然后堆栈视图的高度可能为零 - 因此无法轻触按钮。

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

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

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