gpt4 book ai didi

ios - addArrangedSubview 与 addSubview

转载 作者:搜寻专家 更新时间:2023-10-31 22:37:10 26 4
gpt4 key购买 nike

我是新手,我编写了一个继承自 StackView 的 customView,并以编程方式创建了一个具有少量属性的 button,当我将其添加到我的自定义 View 时,我有两个问题:

  1. 如果我使用 addArrangedSubview(myBtn),我的 View 会忽略那些我添加并填充了整个宽度。但是如果我使用 addSubView(myBtn),没关系(44x44 的蓝色方 block )
  2. 如果我使用 addArrangedSubview(myBtn)addTarget() 不起作用并且myBtn 不可点击,但是当我使用 addSubView(myBtn) 时,它起作用了完美。

这是我的自定义 View 类:

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 enter image description here

addSubView()addArrangedSubview() 有什么区别?为什么会出现这些问题?

最佳答案

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

一个 UIStackView,从它的 .addArrangedSubview() 方法可以猜到,安排它的 subview ,基于它的 .axis.alignment.distribution.spacing 属性,以及它的 框架

因此,请阅读有关 UIStackView 的内容以及如何使用它。最有可能的是,您目前正在使用以下方式限制您的自定义 View :

  • 领导
  • 尾部(或宽度)

因此,将您的按钮添加为 arrangedSubView 会导致它拉伸(stretch)到堆栈 View 的宽度,因为这是默认设置。

将其添加为 subview 只是将按钮覆盖在堆栈 View 上,而不是让堆栈 View 对其进行排列,然后堆栈 View 的高度可能为零——因此按钮无法点击。

尝试在添加自定义堆栈 View 时设置顶部和前导约束。这应该会为您提供一个可以点击的 44 x 44 按钮。

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

关于ios - addArrangedSubview 与 addSubview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55221703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com