【问题标题】:UISearchBar custom cornersUISearchBar 自定义角
【发布时间】:2015-07-20 16:04:08
【问题描述】:

我正在尝试创建这样的搜索栏:

但我注意到我可能不得不用我自己的图像替换搜索栏,因为我设置时搜索栏的角落出现错误:

self.searchController.searchBar.layer.cornerRadius = 50 // I've tried other numbers besides this too with no luck
self.searchController.searchBar.clipsToBounds = true

如果我设置这个:

self.searchController.searchBar.layer.cornerRadius = self.searchController.searchBar.bounds.height/2

搜索栏是这样出来的:

这仍然与图像中的不完全相同。

有没有办法用图像替换文本字段的左侧和右侧,这样我就可以使用自定义搜索栏中的圆角?

【问题讨论】:

    标签: ios swift uitextfield uisearchbar uisearchcontroller


    【解决方案1】:

    我正在使用此代码 UISearchBar,但您可以将此代码与 UISearchController 一起使用。

        let searchBar = UISearchBar()
                    searchBar.sizeToFit()
                    searchBar.placeholder = "Search"
                    navigationItem.titleView = searchBar
    
                    if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
                        textfield.textColor = UIColor.blue
                        if let backgroundview = textfield.subviews.first {
                            // Background color
                            backgroundview.backgroundColor = UIColor.white
                            // Rounded corner
                            backgroundview.layer.cornerRadius = 14;
                            backgroundview.clipsToBounds = true;
                        }
                    }
    

    【讨论】:

      【解决方案2】:

      你应该改变 UISearchBar 内 searchTextField 的半径。

      你可以这样做:

      searchBar.searchTextField.layer.cornerRadius = 20
      searchBar.searchTextField.layer.masksToBounds = true
      

      * searchBar 是 StoryBoard 中 UISearchBar 的一个出口

      【讨论】:

        【解决方案3】:

        这里的问题是你在 UISearchBar 上设置圆角半径,而不是里面的 UITextField。你可以做一些 hack 来获取 UITextField,但这并不是真正推荐的。

        正如您在问题中提到的,您需要使用自定义图像和此处显示的方法:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchBar_Class/#//apple_ref/doc/uid/TP40007529-CH3-SW40

        【讨论】:

          【解决方案4】:

          这在 swift 3 iOS 10 中对我有用:

              searchController.searchBar.layer.cornerRadius = 20
              searchController.searchBar.clipsToBounds = true
          

          【讨论】:

            【解决方案5】:

            搜索栏视图的ez方式

            用于子视图和弹出窗口 [Swift 5]

            override func layoutSublayers(of layer: CALayer) {
                searchBarPopup.clipsToBounds = true
                searchBarPopup.layer.cornerRadius = 10
                searchBarPopup.layer.maskedCorners = [ .layerMaxXMinYCorner, .layerMinXMinYCorner]
            }
            

            【讨论】:

              猜你喜欢
              • 2011-01-29
              • 1970-01-01
              • 2023-03-13
              • 2020-08-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多