将动态类型添加到UISearchBar

时间:2018-07-31 01:57:50

标签: ios swift uisearchbar

我的问题在标题中已经有很多说明。我试图将动态类型(定义为here)添加到UISearchBar中,但没有运气。我知道这是可能的,因为系统应用程序似乎能够很好地处理它,如下所示: enter image description here

但是,我的应用程序的显示效果似乎不如此处所示:

enter image description here

知道UITextField中包含UISearchBar,我自然尝试了此解决方案,但没有成功: UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).adjustsFontForContentSizeCategory = true

我也尝试过在线搜索/检查文档,但似乎找不到任何解决方案。要在UISearchBar中使用动态类型,我缺少什么了。

更新: @matt建议我手动检查并以这种方式更新字体。但是,这又产生了另一个问题,因为搜索栏本身太小,无法容纳如下所示的文本: enter image description here

@matt建议也使用scaledValue(for:)方法来更新高度,但是这似乎不起作用。这是我正在使用的代码:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.preferredFont(forTextStyle: .body)
        let textFieldFrame = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).frame
        UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).frame = CGRect(x: textFieldFrame.minX, y: textFieldFrame.minY, width: textFieldFrame.width, height: UIFontMetrics.default.scaledValue(for: textFieldFrame.height))
}

字体现在似乎正在使用此更新的代码进行缩放,但是搜索栏的高度并未增加:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    searchBar.textField?.font = UIFont.preferredFont(forTextStyle: .body)
    if let textFieldFrame = searchBar.textField?.frame {
        searchBar.textField?.frame = CGRect(x: textFieldFrame.minX, y: textFieldFrame.minY, width: textFieldFrame.width, height: UIFontMetrics.default.scaledValue(for: textFieldFrame.height))
    }
}

此外,这是我找到textField的方式(以防其他陷入困境的用户想知道):

extension UISearchBar {
    var textField: UITextField? {
        var _textField: UITextField? = nil
        subviews.forEach {
            $0.subviews.forEach {
                if let textField = $0 as? UITextField {
                    _textField = textField
                }
            }
        }
        return _textField
    }
}

1 个答案:

答案 0 :(得分:0)

我遵循了这些里程碑,以实现您的目标:

  • 使用动态类型功能(步骤1)自动调整字体。
  • 适应搜索栏约束(STEP 2) 其文本字段约束(STEP 3),当新{{3} }。

    class SearchBarDynamicTypeVC: UIViewController {
    
    @IBOutlet weak var mySearchBar: UISearchBar!
    
    let fontHead = UIFont(name: "Chalkduster", size: 20.0)
    let fontHeadMetrics = UIFontMetrics(forTextStyle: .title1)
    var initialFrameHeight: CGFloat = 0.0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = fontHeadMetrics.scaledFont(for: fontHead!)
    
        mySearchBar.textField?.adjustsFontForContentSizeCategory = true //STEP 1
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        initialFrameHeight = mySearchBar.intrinsicContentSize.height
    
        if let textField = mySearchBar.textField {
            adaptConstraints(textField) //Initialization according to the first preferred content size category
        }
    }
    
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
    
        if let textField = mySearchBar.textField,
            let _ = previousTraitCollection {
    
            adaptConstraints(textField) // STEP 2 & 3
        }
    }
    
    
    private func adaptConstraints(_ textField: UITextField) {
    
    //  Adapt the SEARCHBAR constraints
        mySearchBar.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.deactivate(mySearchBar.constraints)
    
        let heightSB = mySearchBar.heightAnchor.constraint(equalToConstant: fontHeadMetrics.scaledValue(for: initialFrameHeight))
        let widthSB = mySearchBar.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width - 20)
        let centerVSB = mySearchBar.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        let centerHSB = mySearchBar.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
    
        NSLayoutConstraint.activate([centerVSB,
                                     centerHSB,
                                     widthSB,
                                     heightSB])
    
    //  Adapt the SEARCHBAR TEXTFIELD constraints
        textField.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.deactivate(textField.constraints)
    
        let centerXTF = textField.centerXAnchor.constraint(equalTo: textField.superview!.centerXAnchor)
        let centerYTF = textField.centerYAnchor.constraint(equalTo: textField.superview!.centerYAnchor)
        let widthTF = textField.widthAnchor.constraint(equalTo: textField.superview!.widthAnchor, constant: -20.0)
        let heightTF = textField.heightAnchor.constraint(equalTo: textField.superview!.heightAnchor, constant: -20.0)
    
        NSLayoutConstraint.activate([centerXTF,
                                     centerYTF,
                                     widthTF,
                                     heightTF])
    }
    }
    

我使用了帖子中提供的代码段来获取搜索栏文本字段:

extension UISearchBar {

    var textField: UITextField? {

        var _textField: UITextField? = nil

        subviews.forEach {
            $0.subviews.forEach {
                if let textField = $0 as? UITextField {
                    _textField = textField
                }
            }
        }
        return _textField
    }
}

但是,您也可以使用键searchField来获取它,如下所示:

let textField = searchBar.value(forKey: "searchField") as? UITextField

下面的快照显示了最终结果:

preferred content size category

您现在可以通过调整上面的代码段并自定义视觉上的个人选择(文本样式,字体,边距...)将动态类型添加到UISearchBar