簡體   English   中英

在iOS 8上使用Swift設置占位符文本顏色/隱藏取消按鈕

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

我的導航欄中有一個UiSearchbar。 SearchBar樣式很小。 我在iOS 8上,使用SearchController(無SearchDisplayController)和Swift。

  1. 我想將占位符和圖標顏色設置為白色。 這可能嗎? 到目前為止,我發現的所有內容似乎都已過時,或者作者不確定此代碼是否會被Apple批准。

  2. 我想擺脫取消按鈕,但是當我嘗試這樣做時:viewDidLoad中的searchController.searchBar.showsCancelButton = false仍然顯示取消按鈕。

我必須說,我正在以編程方式創建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委托方法並將其隱藏。 只要確保首先添加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