【问题标题】:Change the text layout in a UITextField更改 UITextField 中的文本布局
【发布时间】:2017-02-19 04:19:28
【问题描述】:

下面是一些 UITextFields 的图像。关于底部的大的,我如何让它在左上角(而不是中间)开始文本,以及如何让它们都从右边开始。如您所见,它们笨拙地靠近左边缘。


【问题讨论】:

  • 做左填充。对于文本视图,您必须使用左插图。

标签: ios swift xcode text uitextfield


【解决方案1】:

对于 textField,覆盖以下方法:

class InsetTextField: UITextField {

    var inset: CGFloat = 10

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: 0)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: 0)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: 0)
    }

}

对于文本视图:

textView.contentInset = UIEdgeInsetsMake(inset, inset, inset, inset);

您可以在 textView 完成编辑后参与其中,请查看this question

【讨论】:

  • 您能提供更多细节吗?我要扩展这些类吗?
【解决方案2】:

您可以转接至自定义 TextField:

import UIKit

class CustomTextField: UITextField {

    var inset:CGFloat = 12  // You can set the inset you want

    override func textRect(forBounds bounds: CGRect) -> CGRect {

        return bounds.insetBy(dx: inset, dy: 0)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {

        return bounds.insetBy(dx: inset, dy: 0)
    }

}

结果,你可以看到CustomTextField的插图:


编辑

【讨论】:

  • @Gabe Spound,你可以搜索委托方法。
【解决方案3】:

默认情况下,UITextFields 只有一行。根据您的图片,我假设您希望用户有空间输入段落。对于段落,最好使用 UITextViews。对于您的问题,这将是一个更简单的解决方案。

我总是将 TextViews 用于传记,因为它让我的生活更轻松。

【讨论】:

  • 我不能使用文本视图,因为我需要能够在完成编辑后创建操作,而他们没有该选项。
【解决方案4】:

添加文本字段的左填充

let paddingVie = UIView(frame: CGRect(x: 0, y:0, width: 10, height: 10))
yourtextField.leftView = paddingVie
yourtextField.leftViewMode = .always

为文本视图添加

yourTextVieName.textContainerInset =
   UIEdgeInsetsMake(8,5,8,5); // top, left, bottom, right

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2020-02-02
    相关资源
    最近更新 更多