【问题标题】:how to make autoresize textfield in swift如何在 swift 中自动调整文本字段的大小
【发布时间】:2016-01-04 12:23:41
【问题描述】:

我需要设置一个在键入时自动更改其宽度的 TextField。文本字段的大小应该动态变化。 我找到了以下解决方案,但不知道如何准确使用它 Resize textField Based On Content

【问题讨论】:

    标签: ios swift uitextfield


    【解决方案1】:

    您必须为此使用UITextView 并使用它的sizeThatFits 方法。

    首先你要知道线会走多高

    var totalLines:CGFloat = 5
    var maxHeight:CGFloat = myTextview.font.lineHeight * totalLines
    

    然后在你的viewDidLoad 方法中

    myTextView.sizeThatFits(CGSizeMake(myTextview.frame.size.width, maxHeight))
    

    您在代码中做错了。在viewDidLoad中使用上面的代码

     @IBOutlet weak var myTextview: UITextView!
    
    
    
        override func viewDidLoad()
    
    
        { super.viewDidLoad()
            let totalLines:CGFloat = 5
    
            let maxHeight:CGFloat = (myTextview.font!.lineHeight * totalLines)
    
    
    
            myTextview.sizeThatFits(CGSizeMake(myTextview.frame.size.width, maxHeight))
    
    }
    
        override func didReceiveMemoryWarning() {
    
            super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
    
    }
    

    【讨论】:

    • 编译失败并显示消息“实例成员 'myTextview' 不能用于类型 'ViewController'”。不知道怎么解决?
    • 这里使用您的文本字段名称。我以 mytextfield 为例 @dimple
    • 是的...我使用了我的 textview 名称...我已经为 textview 设置了“myTextview”名称的出口
    • @dimple 你能在这里分享你的viewController代码吗
    • 导入 UIKit 类 ViewController: UIViewController { @IBOutlet weak var myTextview: UITextView! var totalLines:CGFloat = 5 var maxHeight:CGFloat = (myTextview.font.lineHeight * totalLines) 覆盖 func viewDidLoad() { super.viewDidLoad() myTextView.sizeThatFits(CGSizeMake(myTextview.frame.size.width, maxHeight)) } 覆盖func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // 处理所有可以重新创建的资源。 } }
    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2012-07-17
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多