我有一个表视图控制器,我唯一的方法是使用它,所以请不要告诉我使用viewController而不是tableviewController这里是我的代码添加一个按钮,这个按钮显示在最后一个单元格但我想要当用户滚动表格时按钮位于屏幕底部而不移动
override func viewDidLoad() {
super.viewDidLoad()
let submitButton = UIButton(frame: CGRect(x: 5, y: view.frame.origin.y + view.frame.size.height, width: self.view.frame.width - 10 , height: 50))
submitButton.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)
submitButton.setTitle("Submit", for: .normal)
submitButton.titleLabel?.font = UIFont(name: "Arial", size: 15)
submitButton.titleLabel?.textColor = .white
submitButton.addTarget(self, action: #selector(submit), for: .touchUpInside)
submitButton.layer.cornerRadius = 5
view.addSubview(submitButton)
答案 0 :(得分:1)
试试这个
将按钮声明为变量
var submitButton:UIButton!
并在viewDidLoad
中 submitButton = UIButton(frame: CGRect(x: 5, y: UIScreen.main.bounds.size.height - 50 , width: UIScreen.main.bounds.size.width - 10 , height: 50))
submitButton.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)
submitButton.setTitle("Submit", for: .normal)
submitButton.titleLabel?.font = UIFont(name: "Arial", size: 15)
submitButton.titleLabel?.textColor = .white
submitButton.addTarget(self, action: #selector(submit), for: .touchUpInside)
submitButton.layer.cornerRadius = 5
self.view.addSubview(submitButton)
并实施此方法
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
submitButton.frame = CGRect.init(x: submitButton.frame.origin.x, y: UIScreen.main.bounds.size.height + scrollView.contentOffset.y - 50 , width: submitButton.frame.width, height: submitButton.frame.height)
}
答案 1 :(得分:1)
如果适合您的情况,请尝试此方法:
var submitButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
submitButton.frame = CGRect(x: 5, y: view.frame.origin.y + view.frame.size.height, width: self.view.frame.width - 10 , height: 50)
submitButton.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)
submitButton.setTitle("Submit", for: .normal)
submitButton.titleLabel?.font = UIFont(name: "Arial", size: 15)
submitButton.titleLabel?.textColor = .white
submitButton.addTarget(self, action: #selector(submit), for: .touchUpInside)
submitButton.layer.cornerRadius = 5
self.view.window?.addSubview(submitButton)
}
但在这种情况下,您必须从viewWillDisappear
中的超级视图中删除该按钮:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self. submitButton.removeFromSuperview()
}