应用从后台进入前台时自定义搜索栏布局重叠

问题描述 投票:0回答:0
class CustomSearchBar: UISearchBar {
    private let toLabel: UILabel = {
        let label = UILabel()
        label.text = "To:"
        label.textColor = .label
        label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        configureUI()
    }

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

    private func configureUI() {
        self.searchTextField.backgroundColor = .clear
        self.searchTextField.clearButtonMode = .never
        self.backgroundImage = UIImage()
        self.setImage(UIImage(), for: .search, state: .normal)
        self.searchTextField.tokenBackgroundColor = UIColor.secondaryBackgroundColor
        self.tintColor = .label

        // Add "To:" label to the search bar
        self.addSubview(toLabel)
        toLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 12).isActive = true
        toLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

        // Set up the text field to start after the "To:" label
        self.searchTextField.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(self.searchTextField)
        self.searchTextField.leadingAnchor.constraint(equalTo: toLabel.trailingAnchor, constant: 8).isActive = true
        self.searchTextField.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -12).isActive = true
        self.searchTextField.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // Adjust text field frame to prevent overlap with the "To:" label
        let textField = self.searchTextField
        let xValue = toLabel.frame.maxX + 8
        let width = self.frame.width - 12 - xValue - 12
        textField.frame = CGRect(x: xValue, y: textField.frame.minY, width: width, height: textField.frame.height)
    }
}

我如上所述创建了一个自定义搜索栏。搜索栏文本在

To:
标签之后开始。我在
ViewController
中添加了它作为出口。加载视图时它工作正常,但是当我将应用程序从后台移动到前台时,搜索栏文本与
To:
标签重叠。

我尝试在

viewWillLayoutSubview
方法中调用
searchBar.layoutSubviews()
searchBar.layoutIfNeeded()
viewWillAppear
。它没有用。你能建议如何解决这个问题吗?

swift uikit uisearchbar
© www.soinside.com 2019 - 2024. All rights reserved.