问题
I used the following code for setting different font for UITextfield's text(16) and placeholder(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)
Font size is set correctly, but the placeholder text sets somewhat upper in the textfield.
How can I fix this issue? Any Suggestions?
回答1:
I fixed this issue programmatically, since I could not find any other way to fix it.
Code below:
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
}
}
来源:https://stackoverflow.com/questions/33842112/setting-font-for-uitextfield-place-holder-in-swift