ios - 在 iOS 8 上使用 swift 设置占位符文本颜色/隐藏取消按钮

标签 ios swift uisearchbar uisearchcontroller

我的导航栏中有一个 UiSearchbar。 SearchBar 样式是最小的。我在 iOS 8 上,使用 SearchController(没有 SearchDisplayController)和 Swift。

  1. 我想将占位符和图标颜色设置为白色。这可能吗?到目前为止,我发现的所有内容似乎都已过时,或者作者不确定此代码是否会得到 Apple 的批准。

  2. 我想摆脱取消按钮,但是当我尝试这样做时: searchController.searchBar.showsCancelButton = false 在 viewDidLoad 中,取消按钮仍然显示。

我必须说,我正在以编程方式创建 searchBar..

最佳答案

对于第一个问题,您可以访问 UISearchbarUITextField 并编辑占位符颜色:

var textfield:UITextField = searchBar.valueForKey("searchField") as UITextField

//Set the foregroundcolor of the placeholder
var attributedString = NSAttributedString(string: "your placeholdertext", attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])

textfield.attributedPlaceholder = attributedString

然后还要设置玻璃颜色,您必须访问 UITextFieldleftView:

//Get the glass icon
var iconView:UIImageView = textfield.leftView as UIImageView
//Make the icon to a template which you can edit
iconView.image = iconView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
//Set the color of the icon
iconView.tintColor = UIColor.whiteColor()

要隐藏 UISearchbar 中的取消按钮,您可以使用 searchBarShouldBeginEditing 委托(delegate)方法并将其隐藏。只需确保首先添加 UISearchBarDelegate 并将委托(delegate)设置为您的搜索栏:

 class YourviewController:UIViewController, UISearchBarDelegate{

    override func viewDidLoad() {
        searchbar.delegate = self
    }

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        searchBar.setShowsCancelButton(false, animated: true)
        return true
    }
}

关于ios - 在 iOS 8 上使用 swift 设置占位符文本颜色/隐藏取消按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28515078/

相关文章:

ios - FaSTLane:似乎没有为此项目设置 CURRENT_PROJECT_VERSION 键

ios - 关闭模态视图后删除模态模糊效果

ios - 导航栏搜索 View

ios - NSPredicate 的搜索栏不起作用

ios - iOS 7+ 中纯色的 UISearchBar

ios - 在 Collection View 的 performBatchUpdates 崩溃

ios - iOS 和 "invalid_grant"上的 Google 云端硬盘

ios - 选中复选框时 TableView 自动滚动

ios - 如何在 iOS Swift 中正确恢复应用内购买产品

ios - 快速放大位置