首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用UITextBorderStyleNone为UITextField设置填充

使用UITextBorderStyleNone为UITextField设置填充
EN

Stack Overflow用户
提问于 2010-09-16 21:21:27
回答 32查看 222.2K关注 0票数 410

我想为我的UITextFields使用一个自定义的背景。除了我必须使用UITextBorderStyleNone使它看起来更漂亮之外,它工作得很好。这会强制文本在没有任何填充的情况下粘贴到左侧。

除了使用我的自定义背景图像之外,我可以手动设置一个填充,使其看起来与UITextBorderStyleRoundedRect相似吗?

EN

回答 32

Stack Overflow用户

回答已采纳

发布于 2010-12-13 04:20:41

我找到了一个巧妙的小技巧来为这种情况设置左填充。

基本上,将UITextField的leftView属性设置为所需填充大小的空视图:

代码语言:javascript
复制
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

对我来说就像一个护身符!

Swift 3/ Swift 4中,可以这样做

代码语言:javascript
复制
let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
textField.leftView = paddingView
textField.leftViewMode = .always
票数 862
EN

Stack Overflow用户

发布于 2011-06-21 03:16:25

我创建了这个类别实现,并将其添加到.m文件的顶部。

代码语言:javascript
复制
@implementation UITextField (custom)
    - (CGRect)textRectForBounds:(CGRect)bounds {
        return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8,
                          bounds.size.width - 20, bounds.size.height - 16);
    }
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        return [self textRectForBounds:bounds];
    }
@end

基于Piotr Blasiak提供的链接。它看起来比创建一个全新的子类更简单,也比添加额外的UIView更简单。尽管如此,似乎还是缺少一些不能控制文本字段中的填充的东西。

Swift 4解决方案:

代码语言:javascript
复制
class CustomTextField: UITextField {
    struct Constants {
        static let sidePadding: CGFloat = 10
        static let topPadding: CGFloat = 8
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(
            x: bounds.origin.x + Constants.sidePadding,
            y: bounds.origin.y + Constants.topPadding,
            width: bounds.size.width - Constants.sidePadding * 2,
            height: bounds.size.height - Constants.topPadding * 2
        )
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return self.textRect(forBounds: bounds)
    }
}
票数 180
EN

Stack Overflow用户

发布于 2014-12-19 02:28:31

适用于Xcode >6的Swift 3版本,其中您可以在Interface Builder / Storyboard中编辑插入值。

代码语言:javascript
复制
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)
    }

}

票数 143
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3727068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档