gpt4 book ai didi

swift - 使用 stackview 使 UITableView 下拉

转载 作者:行者123 更新时间:2023-11-30 11:59:07 24 4
gpt4 key购买 nike

我试图在单击按钮时实现 UITableView 下拉菜单。最初,tableView 应隐藏,当用户按下按钮时,它应下拉。我一直试图用 UIStackView 来实现这一点,但没有成功。也许我做错了,或者也许有另一种方法可以做到这一点。

let stackView = UIStackView()
var btn: UIButton!
var myTableView = UITableView()

override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
myTableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 1))
myTableView.frame = CGRect(x: 0, y: 0, width: 300, height: 200)
myTableView.center = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
myTableView.showsVerticalScrollIndicator = false

btn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50))
btn.backgroundColor = UIColor.blue.withAlphaComponent(0.3)
btn.setTitle("DropDownMenu", for: UIControlState.normal)
btn.titleLabel?.textColor = .white
btn.titleLabel?.textAlignment = .center
btn.center = CGPoint(x: self.view.frame.width/2, y: myTableView.center.y - myTableView.frame.height/2 - btn.frame.height/2)
btn.addTarget(self, action: #selector(btnPressed), for: UIControlEvents.touchUpInside)

stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing = 16.0
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(btn)
stackView.addSubview(myTableView)
self.view.addSubview(stackView)

}

@objc func btnPressed() {
UIView.animate(withDuration: 1) {
self.myTableView.isHidden = !self.myTableView.isHidden
}
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "This is cell " + indexPath.row.description
cell.textLabel?.textColor = .black
return cell
}

我可以让tableView消失,但没有动画。有什么想法吗?

最佳答案

我最终采用的方法不是通过 UIStackView 而是简单地使用一个按钮来为 tableView 的框架设置动画。框架最初设置为屏幕的宽度和 0 的高度。当用户按下按钮时,我设置高度。

UIView.animate(withDuration: 0.25, animations: {
self.menuTable.frame = CGRect(x: 0, y: (sender.center.y + sender.frame.height/2), width: self.view.frame.width, height: yourHeight)
})

关于swift - 使用 stackview 使 UITableView 下拉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47461334/

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