Установить отступы для UITextField с помощью UITextBorderStyleNone - PullRequest
384 голосов
/ 16 сентября 2010

Я хотел использовать собственный фон для моего UITextFields.Это прекрасно работает, за исключением того факта, что я должен использовать UITextBorderStyleNone, чтобы он выглядел красиво.Это заставляет текст придерживаться влево без каких-либо отступов.

Можно ли вручную установить отступ, чтобы он выглядел как UITextBorderStyleRoundedRect за исключением использования моего собственного фонового изображения?

Ответы [ 32 ]

802 голосов
/ 12 декабря 2010

Я нашел аккуратный небольшой хак для установки левого отступа для этой конкретной ситуации.

По сути, вы устанавливаете свойство leftView UITextField как пустое представление размера нужного вам отступа:

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

Для меня это сработало!*

В Swift 3 / Swift 4 это можно сделать, выполнив это

let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
textField.leftView = paddingView
textField.leftViewMode = .always
166 голосов
/ 20 июня 2011

Я создал реализацию этой категории и добавил ее в начало файла .m.

@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

На основании ссылки, предоставленной Петром Блясиаком. Казалось, проще создать целый новый подкласс, а также проще, чем добавить дополнительный UIView. Тем не менее, кажется, что чего-то не хватает, чтобы не иметь возможности управлять заполнением внутри текстового поля.

Решение Swift 4:

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)
    }
}
132 голосов
/ 18 декабря 2014

Версия 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)
    }

}

enter image description here

68 голосов
/ 27 мая 2014

Редактировать: Все еще работает в iOS 11.3.1

В iOS 6 myTextField.leftView = paddingView; вызывает проблему

Это решает проблему

myTextField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0)

Для выровненного по правому краю текстового поля используйте CATransform3DMakeTranslation(-5, 0, 0) в качестве упоминания latenitecoder в комментариях

68 голосов
/ 10 июля 2013

Хороший подход для добавления отступов в UITextField - это создать подкласс и добавить свойство edgeInsets. Затем вы устанавливаете edgeInsets, и UITextField будет отображаться соответственно. Это также будет правильно работать с пользовательским набором leftView или rightView.

OSTextField.h

#import <UIKit/UIKit.h>

@interface OSTextField : UITextField

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

OSTextField.m

#import "OSTextField.h"

@implementation OSTextField

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsZero;
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        self.edgeInsets = UIEdgeInsetsZero;
    }
    return self;
}

- (CGRect)textRectForBounds:(CGRect)bounds {
    return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

@end
25 голосов
/ 08 августа 2013

Просто подкласс UITextField, как это:

@implementation DFTextField


- (CGRect)textRectForBounds:(CGRect)bounds
{
    return CGRectInset(bounds, 10.0f, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return [self textRectForBounds:bounds];
}


@end

Это добавляет горизонтальный отступ 10 пунктов с каждой стороны.

21 голосов
/ 28 апреля 2015

Код цели C

MyTextField.h

#import <UIKit/UIKit.h>

@interface MyTextField : UITextField

@property (nonatomic) IBInspectable CGFloat padding;

@end

MyTextField.m

#import "MyTextField.h"

IB_DESIGNABLE
@implementation MyTextField

@synthesize padding;

-(CGRect)textRectForBounds:(CGRect)bounds{
    return CGRectInset(bounds, padding, padding);
}

-(CGRect)editingRectForBounds:(CGRect)bounds{
    return [self textRectForBounds:bounds];
}

@end

enter image description here

19 голосов
/ 11 августа 2015
  1. Создание текстового поля Custom

PaddingTextField.swift

import UIKit
class PaddingTextField: UITextField {

@IBInspectable var paddingLeft: CGFloat = 0
@IBInspectable var paddingRight: CGFloat = 0

override func textRectForBounds(bounds: CGRect) -> CGRect {
    return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
        bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
}

override func editingRectForBounds(bounds: CGRect) -> CGRect {
    return textRectForBounds(bounds)
}}

Установите класс текстового поля равным PaddingTextField и настройте свой отступ по своему усмотрению enter image description here enter image description here

Наслаждайтесьэто

final

19 голосов
/ 20 января 2014

Основываясь на ответе Evil Trout, вы можете создать категорию, чтобы упростить ее использование в нескольких приложениях.

Заголовочный файл:

@interface UITextField (PaddingText)

-(void) setLeftPadding:(int) paddingValue;

-(void) setRightPadding:(int) paddingValue;
@end

Файл реализации:

#import "UITextField+PaddingText.h"

@implementation UITextField (PaddingText)

-(void) setLeftPadding:(int) paddingValue
{
    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
    self.leftView = paddingView;
    self.leftViewMode = UITextFieldViewModeAlways;
}

-(void) setRightPadding:(int) paddingValue
{
    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
    self.rightView = paddingView;
    self.rightViewMode = UITextFieldViewModeAlways;
}

@end

Пример использования

#import "UITextField+PaddingText.h"

[self.YourTextField setLeftPadding:20.0f];

Надеюсь, это поможет вам, ребята

Приветствия

12 голосов
/ 10 октября 2014

Swift версия:

extension UITextField {
    @IBInspectable var padding_left: CGFloat {
        get {
            LF.log("WARNING no getter for UITextField.padding_left")
            return 0
        }
        set (f) {
            layer.sublayerTransform = CATransform3DMakeTranslation(f, 0, 0)
        }
    }
}

Так что вы можете присвоить значение в IB

IBInspectable setting represented in Interface Builder

...