swift - 向 UITextField 添加顶部填充

标签 swift uitextfield

我正在尝试将顶部填充添加到文本字段,但找不到任何有用的东西,所有解决方案都是关于我已经知道的左右填充。为了清楚起见,我想让它像下图一样。

注意:我为“描述”使用了标签,并将其放在文本字段中,但标签和输入重叠了。

Text Field Design

最佳答案

使用自定义文本字段类

class CustomTextField: UITextField {

    let padding = UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0);

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, padding)
    }
}

Swift 4 版本,根据下面 Micah 的回答:

class CustomTextField: UITextField {

    let padding = UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0);

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }
}

关于swift - 向 UITextField 添加顶部填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49199163/

相关文章:

ios - 从使用 CALayer 设置样式的 UITextField 中的占位符文本中删除阴影

ios - 无法弄清楚为什么过早释放对象

如果使用 setter 和 getter,则 Swift Decode 不起作用

ios - 如何在 TableView 单元格之间进行分隔

ios UITextField 使用 uidatepicker 进行编辑

ios - 如何固定所有 iPhone 设备中的文本字段位置?

ios - 如果在 Parse 中设置为 true,如何仅在我的 PFQueryTableViewController 中显示项目 - Swift

ios - 尝试在 Swift 项目中使用 Objective C cocoa pod,桥接文件编译为 Swift 代码

ios - 为UIPickerView didSelectRow返回NSArray中字符串的第一个字符

ios - 清除 secureTextEntry = YES 的 UITextField 时是否触发事件?