为 swift 中的 UITextfield 占位符设置字体
Setting font for UITextfield place holder in swift
我使用以下代码为 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)
字体大小设置正确,但占位符文本在文本字段中设置得稍靠上。
我该如何解决这个问题?有什么建议吗?
我以编程方式解决了这个问题,因为我找不到任何其他方法来解决它。
代码如下:
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
}
}
我使用以下代码为 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)
字体大小设置正确,但占位符文本在文本字段中设置得稍靠上。
我该如何解决这个问题?有什么建议吗?
我以编程方式解决了这个问题,因为我找不到任何其他方法来解决它。
代码如下:
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
}
}