ios - 标题中的 Swift 可扩展搜索栏?

标签 ios swift xcode

我有一个表格 View ,我希望能够对其进行搜索。我知道该怎么做,但是有没有一种方法可以让我的表格 View 标题中的条形按钮项扩展到搜索条(具有一定宽度)?例如,我可以在 swift 中制作类似下面的内容吗?

Expandable Search Bar

最佳答案

这是一个工作示例:

enter image description here

class ExpandableView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .green
        translatesAutoresizingMaskIntoConstraints = false

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override var intrinsicContentSize: CGSize {
        return UILayoutFittingExpandedSize
    }
}


class ViewController: UIViewController {

    var leftConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        assert(navigationController != nil, "This view controller MUST be embedded in a navigation controller.")

        // Expandable area.
        let expandableView = ExpandableView()
        navigationItem.titleView = expandableView

        // Search button.
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(toggle))

        // Search bar.
        let searchBar = UISearchBar()
        searchBar.translatesAutoresizingMaskIntoConstraints = false
        expandableView.addSubview(searchBar)
        leftConstraint = searchBar.leftAnchor.constraint(equalTo: expandableView.leftAnchor)
        leftConstraint.isActive = false
        searchBar.rightAnchor.constraint(equalTo: expandableView.rightAnchor).isActive = true
        searchBar.topAnchor.constraint(equalTo: expandableView.topAnchor).isActive = true
        searchBar.bottomAnchor.constraint(equalTo: expandableView.bottomAnchor).isActive = true
    }

    @objc func toggle() {

        let isOpen = leftConstraint.isActive == true

        // Inactivating the left constraint closes the expandable header.
        leftConstraint.isActive = isOpen ? false : true

        // Animate change to visible.
        UIView.animate(withDuration: 1, animations: {
            self.navigationItem.titleView?.alpha = isOpen ? 0 : 1
            self.navigationItem.titleView?.layoutIfNeeded()
        })
    }
}

关于ios - 标题中的 Swift 可扩展搜索栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38580175/

相关文章:

ios - 多个 ViewController 调用的函数的 NSTimer 目标

ios - UITextView 内容插入

ios - 具有多个图像和标签的自定义单元格显示不一致

ios - 应用程序版本 IOS 7 & IOS 9

iphone - 基于内容 ios 的动态单元格高度

ios - 添加被邀请者时,EKEventEditViewController SGErrorDomain代码= 8

ios - 如何在标签中添加按钮?

ios - 字典比较数组

ios - 将自定义颜色设置为 UITabBarItem 不起作用

ios - 如何从 Storyboard 设置 Split View Controller Delegate?