【问题标题】:How do I add a floating UIButton to Table View Controller in Xcode?如何在 Xcode 中将浮动 UIButton 添加到表视图控制器?
【发布时间】:2019-10-07 09:14:06
【问题描述】:

我正在尝试向通过弹出窗口显示的表格视图控制器页面添加“关闭”按钮。当用户向下滚动页面时,我只希望 x(关闭)按钮保留在左上角。我找到了使用 cocoapods 添加浮动操作按钮的代码,但这不是我想要的。任何帮助都会很棒。

我尝试在表格视图之外添加一个 UIView,以便我可以将按钮限制在该按钮上,但表格视图不允许您在其外部添加 UIView。

【问题讨论】:

    标签: swift xcode uibutton floating


    【解决方案1】:

    您无法将浮动 UIButton 添加到 UITableViewController,但您还有其他三个选项:

    1. UITableViewController更改为UIViewController并将UITableViewUIButton添加到视图控制器
    2. 创建UIViewController 容器并将UITableViewController 添加为嵌入式子视图控制器。然后你可以将UIButton添加到容器中
    3. UIButton 添加到UINavigationController,但只有在您有导航控制器时才会起作用:) 此外,在这种方法中,您需要在关闭表格视图控制器时手动删除按钮。

    【讨论】:

    • 谢谢 Michcio,我害怕这个答案 :) 我已经建立了我的页面,这花了我很长时间。但我认为你的选项 1 是最好的选择。我只需要使用 UIViewControllers 重新构建它们并将表格视图添加到其中。
    【解决方案2】:

    如果将 UIButton 嵌入到 UIView 中,则可以使用 UITableVIewController。

    这是我的 UITableViewController 实例之一的精简代码。有一个 UITableView,页面底部有一个 UIView,上面有一个 UIButton:

    class ViewController : UITableViewController
    {
        @IBOutlet private weak var floatingView: UIView!
    
        override func viewDidLoad()
        {
            super.viewDidLoad()
    
            self.initSaveView()
        }
    
        override func viewWillLayoutSubviews()
        {
            super.viewWillLayoutSubviews()
    
            self.tableView.bringSubviewToFront(self.floatingView)
        }
    
        fileprivate func initSaveView()
        {
            self.tableView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.floatingView.frame.height, right: 0.0)
            self.tableView.scrollIndicatorInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.floatingView.frame.height, right: 0.0)
    
            self.floatingView.frame.origin.y = self.tableView.bounds.origin.y + self.tableView.frame.height - floatingView.frame.height
            self.floatingView.autoresizingMask = .flexibleTopMargin
            self.view.addSubview(self.floatingView)
        }
    }
    
    extension ViewController
    {
        override func scrollViewDidScroll(_ scrollView: UIScrollView)
        {
            floatingView.frame = CGRect(x: self.floatingView.frame.origin.x, y: self.tableView.bounds.origin.y + self.tableView.frame.height - floatingView.frame.height, width: self.floatingView.frame.size.width, height: self.floatingView.frame.size.height)
        }
    }
    

    希望这能让您入门。 floatingView 是使用 Interface Builder 添加的(只需将 UIView 拖到 UITableViewController 栏的顶部,然后添加您的 Outlet)。

    【讨论】:

    • 感谢 inexcitus。我试过了,但不幸的是它没有用。 UIView 在我滚动时移动。
    • 您是否更改了 autoresizingMask?如果您希望按钮保持在顶部(而不是页面底部),那么您可能需要尝试将 autoResizingMask 设置为 .flexibleBottomMargin
    • 是的,我试过了,恐怕它仍然会随着屏幕滚动。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2020-09-06
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多