2015-11-21 87 views
2

的UITextField佔位設置字體我用下面的代碼爲UITextField的文本(16)和佔位符(9)設定不同的字體,用於迅速

m_searchTextField.font = UIFont .systemFontOfSize(16) 
let font = UIFont .systemFontOfSize(9) 
let attributes = [ 
     NSForegroundColorAttributeName: UIColor.lightGrayColor(), 
     NSFontAttributeName : font] 

m_searchTextField.attributedPlaceholder = NSAttributedString(string: "Search String be in meddle left", 
     attributes:attributes) 

字體大小設置正確,但佔位符文本集在文本字段中稍高一些。

enter image description here

我怎樣才能解決這個問題?有什麼建議麼?

+0

http://stackoverflow.com/questions/27652227/text-view-placeholder-swift/28271069#28271069 – clearlight

回答

2

我以編程方式解決了這個問題,因爲我找不到任何其他方法來修復它。下面

代碼:

class ViewController: UIViewController { 

    @IBOutlet weak var textField: UITextField! 
    var placeholder : UILabel! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     placeholder = UILabel(frame: CGRect(x: 0, y: 0, width: textField.bounds.width, height: textField.bounds.height)) 
     placeholder.text = "Search String be in meddle left" 
     placeholder.font = UIFont.italicSystemFontOfSize(9) 
     placeholder.textColor = UIColor.grayColor() 
     placeholder.hidden = !textField.text!.isEmpty 
     placeholder.textAlignment = .Center 
     textField.addSubview(placeholder) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    @IBAction func textField_EditingChanged(sender: AnyObject) { 
     placeholder.hidden = !textField.text!.isEmpty 
    } 
}