我想为我的UITextFields使用一个自定义背景。这很好,除了我必须使用UITextBorderStyleNone来使它看起来很漂亮。这将迫使文本保持在左边,没有任何填充。

我可以手动设置填充,使它看起来类似于UITextBorderStyleRoundedRect除了使用我的自定义背景图像?


当前回答

下面是一个Swift代码,在UITextfield中提供填充

 func txtPaddingVw(txt:UITextField) {
     let paddingView = UIView(frame: CGRectMake(0, 0, 10, 10))
     txt.leftViewMode = .Always
     txt.leftView = paddingView
 }

调用using

self.txtPaddingVw(txtPin)

其他回答

布洛迪的方法对我很有效。我不得不在文本框上添加侧视图,并添加额外的填充。因此,通过实现自定义UIEdgeInsets属性到UITextField子类,我已经成功实现了任务。我将在所有项目中使用这个新子类。

你不能设置填充。而是有一个UIView,里面有你的背景图像和UITextField。设置UITextField的宽度为UIViewWidth-(paddingSize x 2)和高度相似,然后设置它在点paddingSize,paddingSize。

以下是如何在SWIFT中实现这一点

@IBOutlet weak var yourTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
let paddingView = UIView(frame: CGRectMake(0, 0, 10, self.yourTextField.frame.height))
yourTextField.leftView = paddingView
yourTextField.leftViewMode = UITextFieldViewMode.Always
}
}

资源

一个Swift 3版本的Xcode >6,在那里你可以在接口生成器/故事板编辑插入值。

import UIKit

@IBDesignable
class FormTextField: UITextField {

    @IBInspectable var inset: CGFloat = 0

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

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

}

为什么不是带属性字符串!?!,这是IOS 6.0的祝福功能之一:)

NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
            mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;

textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];