gpt4 book ai didi

ios - 快速动态添加按钮

转载 作者:行者123 更新时间:2023-11-28 06:18:23 25 4
gpt4 key购买 nike

我正在编写一个 iOS 应用程序。服务器给我按钮数组以在 View 上绘制。所以,按钮的数量可以根据服务器响应而变化,示例:

let buttonArray=["Button 1","Button 2","Button 3"]
or
let buttonArray=["Button 1","Button 2","Button 3"," Button 4", "Button 5"]

我必须垂直堆叠这些按钮。我创建了一个 stackview,向其添加constraints,然后将按钮作为 arrangedsubviewsadd 按钮添加到此 stackview。按钮之间应该有 5 点的间距:

使用堆栈 View :

func addButtonsUsingStackView()
{
//create stackview:
let stackView=UIStackView()
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.alignment = .fill
stackView.spacing = 5
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)

//stackview constraints:
let viewsDictionary = ["stackView":stackView]
let stackView_H = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-20-[stackView]-20-|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: viewsDictionary)
let stackView_V = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-30-[stackView]-30-|",
options: NSLayoutFormatOptions(rawValue:0),
metrics: nil,
views: viewsDictionary)
view.addConstraints(stackView_H)
view.addConstraints(stackView_V)

//adding buttons to stackview:

//let buttonArray=["Button 1","Button 2","Button 3"]
let buttonArray=["Button 1","Button 2","Button 3"," Button 4"]

for buttonName in buttonArray{

let button=UIButton()
button.setTitle(buttonName, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.backgroundColor=UIColor.blue
button.translatesAutoresizingMaskIntoConstraints=false

stackView.addArrangedSubview(button)

}

}

没有堆栈 View :

var buttonArray=["Button 1","Button 2","Button 3"," Button 4"," Button 5"," Button 6"," Button 7"]

func addButtonsLoop()
{

for _view in view.subviews{
_view.removeFromSuperview()
}

var i=0
var buttonY = 20
let buttonGap=5

for btn in buttonArray {

let buttonHeight=Int(Int(view.frame.height) - 40 - (buttonArray.count * buttonGap))/buttonArray.count
print(buttonHeight)
let buttonWidth=Int(view.frame.width - 40)

let button = UIButton()
button.backgroundColor = UIColor.orange
button.setTitle(btn, for: .normal)
button.titleLabel?.textColor = UIColor.white
button.frame = CGRect(x: 20, y: buttonY, width:buttonWidth , height:buttonHeight)
button.contentMode = UIViewContentMode.scaleToFill
buttonY += buttonHeight + buttonGap
button.tag = i
button.addTarget(self, action: #selector(self.buttonTapped(_:)), for: UIControlEvents.touchUpInside)
view.addSubview(button)

i+=1

}
}

func buttonTapped( _ button : UIButton)
{
buttonArray.remove(at: button.tag)
addButtonsLoop()
}

我的问题是,除了上面的代码,如何应用 NSLayoutConstraintsLayoutAnchors 来解决这个问题?

最佳答案

您可以使用包含按钮的表格 View 单元格代替堆栈 View ,行数可以是按钮数组计数。在 cellForRowAtIndexPath 委托(delegate)方法中,从按钮数组设置按钮标题。

关于ios - 快速动态添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44409412/

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