搜索栏 - 导航栏中的取消按钮

时间:2015-08-15 15:01:30

标签: ios swift button searchbar

我正在导航栏中搜索栏。当我正在编辑时,我在导航栏的右侧没有取消按钮。

试过:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

    var barButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Done, target: self, action: "")
    self.navigationItem.rightBarButtonItem = barButton
}

enter image description here

enter image description here

编辑:

我在搜索栏中添加了搜索栏,如下所示:

lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 300, 20))

        searchBar.placeholder = "Hľadať"
        searchBar.barStyle = UIBarStyle.BlackTranslucent
        var leftNavBarButton = UIBarButtonItem(customView:searchBar)
        self.navigationItem.leftBarButtonItem = leftNavBarButton

2 个答案:

答案 0 :(得分:1)

以这种方式做到:

// This sets the textcolor for all navigation bars in the app
// Do this in the app delegate on startup
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

在“取消”处理程序中:

searchBar.delegate = self

并为导航栏标题文本设置正确的颜色:

func randomInRangeScale(scale : CGFloat) -> CGFloat {
    let random = arc4random_uniform(UInt32(UInt16.max))
    let randomCGFloat = CGFloat(random)
    return randomCGFloat * 0.000015 + 0.8
}

添加委托:

{{1}}

答案 1 :(得分:0)

如果这是Objective-C回答:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES];
}

然后这可能是Swift的回答:(不是100%肯定)

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchBar.showsCancelButton = true
}

请记住将您的代表与自己联系起来。

来源:UISearchBar Class Reference