Setting font for UITextfield place holder in swift

梦想的初衷 提交于 2019-12-11 01:12:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!