Подтвердить что ты не робот

UITextField только верхняя и нижняя граница

В настоящее время я имею регулярную границу. Я бы хотел, чтобы имел только верхнюю и нижнюю границу.

Как это сделать?

Используя свойство UITextField layer, у меня есть следующий код:

    self.layer.borderColor = [[UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f] CGColor];
    self.layer.borderWidth = 4.0f;

У меня есть способ заставить его работать , делая мой UITextField длинным, так что пользователь не видит левую и правую границы, но мне просто интересно, было ли лучше, хакерский способ сделать это?

У меня проверены документы, а изменение UITextField borderStyle не имеет этой опции.

С

Первый таймер iOS

4b9b3361

Ответ 1

Один подход, который я нашел, работает хорошо, это использование слоев. Вот фрагмент:

CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, self.frame.size.height - 1, self.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor blackColor].CGColor;
[myTextField.layer addSublayer:bottomBorder];

Надеюсь, это поможет кому-то.

Ответ 2

@user3075378 отличный и простой пример в Swift

var bottomBorder = CALayer()
bottomBorder.frame = CGRectMake(0.0, textField.frame.size.height - 1, textField.frame.size.width, 1.0);
bottomBorder.backgroundColor = UIColor.blackColor().CGColor
textField.layer.addSublayer(bottomBorder)

Ответ 3

@Sebyddd зачем останавливаться на достигнутом? (

РЕДАКТИРОВАТЬ: Возникает проблема с отображением строк до того, как автомат устанавливает правильный кадр для представления, я отредактировал свой ответ с исправлением: он в основном включает вызов drawLines() в layoutSubviews()

class FramedTextField: UITextField {

    @IBInspectable var linesWidth: CGFloat = 1.0 { didSet{ drawLines() } }

    @IBInspectable var linesColor: UIColor = UIColor.blackColor() { didSet{ drawLines() } }

    @IBInspectable var leftLine: Bool = false { didSet{ drawLines() } }
    @IBInspectable var rightLine: Bool = false { didSet{ drawLines() } }
    @IBInspectable var bottomLine: Bool = false { didSet{ drawLines() } }
    @IBInspectable var topLine: Bool = false { didSet{ drawLines() } }



    func drawLines() {

        if bottomLine {
            add(CGRectMake(0.0, frame.size.height - linesWidth, frame.size.width, linesWidth))
        }

        if topLine {
            add(CGRectMake(0.0, 0.0, frame.size.width, linesWidth))
        }

        if rightLine {
            add(CGRectMake(frame.size.width - linesWidth, 0.0, linesWidth, frame.size.height))
        }

        if leftLine {
            add(CGRectMake(0.0, 0.0, linesWidth, frame.size.height))
        }

    }

    typealias Line = CGRect
    private func add(line: Line) {
        let border = CALayer()
        border.frame = line
        border.backgroundColor = linesColor.CGColor
        layer.addSublayer(border)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        drawLines()
    }

}

Ответ 4

вы можете создать одно изображение с верхней и нижней границей и установить его на фон вашего UITextField:

yourTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourBorderedImageName"]];

Ответ 5

Вы также можете добавлять представления сверху и снизу для использования в качестве границ.

// Top border
UIView *topBorder = [[UIView alloc]
    initWithFrame:CGRectMake(0,
                             0,
                             textfield.frame.size.width,
                             4.0f)];
topBorder.backgroundColor = [UIColor colorWithRed:160/255.0f
                                            green:160/255.0f
                                             blue:160/255.0f
                                            alpha:1.0f];
[textfield addSubview:topBorder];

// Bottom border
UIView *bottomBorder = [[UIView alloc]
    initWithFrame:CGRectMake(0,
                             textfield.frame.origin.y +
                                 textfield.frame.size.height - 4.0f,
                             textfield.frame.size.width,
                             4.0f)];
bottomBorder.backgroundColor = [UIColor colorWithRed:160/255.0f
                                               green:160/255.0f
                                                blue:160/255.0f
                                               alpha:1.0f];
[textfield addSubview:bottomBorder];

Ответ 6

Вы можете использовать слои для добавления линий/фигур в любой подкласс UIView. Этот код рисует две строки в верхней и нижней частях текстового поля. Вы можете добавить его в подкласс элемента управления или вызвать его непосредственно в родительском представлении/контроллере представления.

CGRect layerFrame = CGRectMake(0, 0, _usernameField.frame.size.width, _usernameField.frame.size.height);
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, layerFrame.size.width, 0); // top line
CGPathMoveToPoint(path, NULL, 0, layerFrame.size.height);
CGPathAddLineToPoint(path, NULL, layerFrame.size.width, layerFrame.size.height); // bottom line
CAShapeLayer * line = [CAShapeLayer layer];
line.path = path;
line.lineWidth = 2;
line.frame = layerFrame;
line.strokeColor = [UIColor blackColor].CGColor;
[_usernameField.layer addSublayer:line];

Ответ 7

Swift 3: Очистите с помощью AutoLayout (я использую здесь PureLayout, но вы также можете сделать это с помощью общего NSLayoutConstraint:

func makeUnderline(for textField: UITextField) {
    let borderLine = UIView()
    borderLine.backgroundColor = UIColor.black
    borderLine.autoSetDimension(.height, toSize: 1)
    textField.addSubview(borderLine)
    borderLine.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .top)
}

Ответ 8

Я предлагаю вам поместить один вид в левой части текстового поля и один вид в правой части текстового поля, чтобы закрыть левую/правую границу.

UIView *v1 = [[UIView all] initWithFrame:CGRectMake(textfield.frame.origin.x - 5, textfield.frame.origin.y, 10, textifield.frame.size.height)];
UIView *v2 = [[UIView all] initWithFrame:CGRectMake(textfield.frame.origin.x + textfield.frame.size.with - 5, textfield.frame.origin.y, 10, textifield.frame.size.height)];

Ответ 9

Надеюсь, что это поможет, поместите это в класс переопределения текстового поля

UIView *view = [[UIView alloc] init];
        view.translatesAutoresizingMaskIntoConstraints = NO;
        view.layer.borderWidth = 1;
        view.backgroundColor = [UIColor blackColor];
        [self addSubview:view];

        [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:1.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:1.0]];

Ответ 10

Благодаря пользователю3075378. мой ответ основан на его. добавив правую и левую маленькие строки.

- (void)styleSearchTextField {
    CALayer *bottomBorder = [CALayer layer], *leftBorder = [CALayer layer], *rightBorder = [CALayer layer];

    CGFloat thickness = 1.0f;
    CGFloat side_height = 6.0f;

    bottomBorder.frame = CGRectMake(0.0f, searchTextField.frame.size.height - 1, searchTextField.frame.size.width, thickness);

    leftBorder.frame = CGRectMake(0.0f, searchTextField.frame.size.height - side_height, thickness, searchTextField.frame.size.height - 1);

    rightBorder.frame = CGRectMake(searchTextField.frame.size.width - 1, searchTextField.frame.size.height - side_height, thickness, searchTextField.frame.size.height - 1);

    bottomBorder.backgroundColor = [self.stylingDetails themeGrayColor].CGColor;
    leftBorder.backgroundColor = [self.stylingDetails themeGrayColor].CGColor;
    rightBorder.backgroundColor = [self.stylingDetails themeGrayColor].CGColor;

    [searchTextField.layer addSublayer:bottomBorder];
    [searchTextField.layer addSublayer:leftBorder];
    [searchTextField.layer addSublayer:rightBorder];
}