为什么我的UISearchBar不服从约束?

时间:2016-08-11 16:34:26

标签: ios swift uiview autolayout uisearchbar

在我的iOS应用中,我的导航栏由UISearchBar中的UIButtonUIStackView组成。由于我无法使用UISearchController故事板,因此我在堆栈视图中有一个空白UIView,并且我将UISearchBar添加为子视图。这是我的故事板的样子:enter image description here

这是我添加搜索栏的代码

override func viewDidLoad() {
    super.viewDidLoad()
    configureSearchController()
    print(wrapperView.bounds)
    print(searchController.searchBar.bounds)
}

func configureSearchController() {
    searchController = UISearchController(searchResultsController: nil)
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search here..."
    searchController.searchBar.sizeToFit()
    searchController.searchBar.isTranslucent = false
    searchController.searchBar.delegate = self
    searchController.delegate = self
    searchController.searchBar.barTintColor = addButton.backgroundColor
    wrapperView.addSubview(searchController.searchBar)
    let color = addButton.backgroundColor
    searchController.searchBar.layer.borderWidth = 1
    searchController.searchBar.layer.borderColor = color?.cgColor
    searchController.searchBar.trailingAnchor.constraint(equalTo: addButton.leadingAnchor)
}

但搜索栏会超过UIButton,如下所示: enter image description here 如何让UISearchBarUIButton这样结束? enter image description here

2 个答案:

答案 0 :(得分:0)

尝试更换:

searchController.searchBar.trailingAnchor.constraint(equalTo: addButton.leadingAnchor)

使用:

searchController.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: nil, metrics: nil, views: ["subview": searchController]))
wrapperView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: nil, metrics: nil, views: ["subview": searchController]))

修改 否则尝试使用UISearchController:

searchController.searchBar.setImage(<image_name>, forSearchBarIcon: .Bookmark, state: .Normal)

这将允许您在搜索栏附近添加自定义按钮。

答案 1 :(得分:0)

我遇到了同样的问题,在将searchController.searchBar.sizeToFit()添加到我的视图后(addSubview()行之后),我可以通过调用wrapperView.layoutIfNeeded()来修复它。您可能必须先运行wrapperView.addSubview(searchController.searchBar) wrapperView.layoutIfNeeded() searchController.searchBar.sizeToFit() ,所以这样的事情:

@echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

SET "src=T:\CNC-Related\CNC Programs\Biesse\Rover346\01 MAIN\S-LINE\SLE"
SET "dst=U:\Users\Edimar\PROJECTS\REPLACE LOCKING BAR\CST640\S-Line\PROGRAM\R346"
SET "file_list=.\files.txt"
SET "out=.\result.log"
echo > %out%

FOR /F "usebackq eol=| delims=" %%f IN ("%file_list%") DO (
    rem just searching to find out existense of file
    WHERE /Q /R %src% "%%f"
    IF "!ERRORLEVEL!" == "0" (
        FOR /F "usebackq eol=| delims=" %%s IN (`WHERE /R %src% "%%f"`) DO (
            echo "%%s => %dst%\%%f" >> %out%
            @Xcopy /y "%%s" "%dst%\%%f" 
        )
    ) ELSE (
        echo %%f is not found! >> %out%
    )
)

希望它有所帮助!