Can the height of the UISearchbar TextField be modified?

后端 未结 8 889
-上瘾入骨i
-上瘾入骨i 2020-12-05 04:34

I\'m testing out my UI and I find the search bar a little bit too narrow for my liking. I also want to make sure people with poorer vision or poorer manual dexterity have n

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 04:54

    Based on thelearner's answer here's the code for Swift 5.* :

    extension UISearchBar {
        func updateHeight(height: CGFloat, radius: CGFloat = 8.0) {
            let image: UIImage? = UIImage.imageWithColor(color: UIColor.clear, size: CGSize(width: 1, height: height))
            setSearchFieldBackgroundImage(image, for: .normal)
            for subview in self.subviews {
                for subSubViews in subview.subviews {
                    if #available(iOS 13.0, *) {
                        for child in subSubViews.subviews {
                            if let textField = child as? UISearchTextField {
                                textField.layer.cornerRadius = radius
                                textField.clipsToBounds = true
                            }
                        }
                        continue
                    }
                    if let textField = subSubViews as? UITextField {
                        textField.layer.cornerRadius = radius
                        textField.clipsToBounds = true
                    }
                }
            }
        }
    }
    
    private extension UIImage {
        static func imageWithColor(color: UIColor, size: CGSize) -> UIImage? {
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            color.setFill()
            UIRectFill(rect)
            guard let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() else {
                return nil
            }
            UIGraphicsEndImageContext()
            return image
        }
    }
    

    and here's how we can apply it:

    searchBar?.setSearchTextField(height: 48)
    

    and here's the result:

提交回复
热议问题