您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Swift:修改 UISearchBar 取消按鈕的文字與顏色

編輯:iOS 7 技巧

下面來看一篇關於 Swift 修改搜索條(UISearchBar)中取消按鈕文字與顏色的示例,希望這篇教程能幫助到各位。

在使用搜索欄(UISearchBar)時,如果把它設置為「Shows Cancel Button」,輸入框右側便會出現一個取消按鈕(標題文字為 Cancel)。

有時我們希望能把這個按鈕改成其他文字,比如「搜索」。雖然 searchBar 並未提供直接修改該按鈕文字的方法或屬性,但我們可以換個思路來實現。

一、修改 searchBar 取消按鈕的文字

先拿到 searchBar 中的取消按鈕,再設置它的 title 即可。

import UIKit
 
class ViewController: UIViewController {
 
    @IBOutlet weak var searchBar: UISearchBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
         
        let uiButton = searchBar.valueForKey("cancelButton") as! UIButton
        uiButton.setTitle("搜索", forState: UIControlState.Normal)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

二、修改 searchBar 取消按鈕的文字顏色

同樣先取得 searchBar 中的取消按鈕,再設置它的 titleColor 即可。

import UIKit
 
class ViewController: UIViewController {
    
    @IBOutlet weak var searchBar: UISearchBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
         
        let uiButton = searchBar.valueForKey("cancelButton") as! UIButton
        uiButton.setTitle("搜索", forState: UIControlState.Normal)
        uiButton.setTitleColor(UIColor.orangeColor(),forState: .Normal)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved