简体   繁体   English

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

[英]Setting the placeholder text color / hiding the cancel Button using swift on iOS 8

I have a UiSearchbar within my Navigation Bar. 我的导航栏中有一个UiSearchbar。 The SearchBar style is minimal. SearchBar样式很小。 I am on iOS 8, using a SearchController (no SearchDisplayController) and Swift. 我在iOS 8上,使用SearchController(无SearchDisplayController)和Swift。

  1. I would like to set the placeholder and the icon color to white. 我想将占位符和图标颜色设置为白色。 Is this possible? 这可能吗? All that I've found so far seems to be outdated or the author is not sure whether this code will be approved by Apple. 到目前为止,我发现的所有内容似乎都已过时,或者作者不确定此代码是否会被Apple批准。

  2. I would like to get rid of the cancel Button, but when I try this: searchController.searchBar.showsCancelButton = false within the viewDidLoad, the cancel button still shows up. 我想摆脱取消按钮,但是当我尝试这样做时:viewDidLoad中的searchController.searchBar.showsCancelButton = false仍然显示取消按钮。

I must say, I am creating the searchBar programmatically.. 我必须说,我正在以编程方式创建searchBar。

For your first problem, you could access the UITextField of your UISearchbar and edit the placeholder color: 对于第一个问题,您可以访问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

Then to also set the glass-color you have to access the leftView of your UITextField : 然后还要设置玻璃颜色,您必须访问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()

To hide the cancel-button in your UISearchbar you can use the searchBarShouldBeginEditing delegate method and hide it. 要在UISearchbar隐藏取消按钮,可以使用searchBarShouldBeginEditing委托方法并将其隐藏。 Just make sure to add the UISearchBarDelegate first and set the delegate to your searchbar: 只要确保首先添加UISearchBarDelegate并将委托设置为您的搜索栏即可:

 class YourviewController:UIViewController, UISearchBarDelegate{

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM