ios UITextField 仅顶部和底部边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15562438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:49:32  来源:igfitidea点击:

UITextField Only Top And Bottom Border

iosobjective-ccocoa-touchuitextfield

提问by GangstaGraham

I currently have a regular border. I would like to only have a top and bottom border.

我目前有一个普通的边界。我只想有一个顶部和底部边框

How do I accomplish this?

我该如何实现?

Using the UITextField's layerproperty, I have the following code:

使用UITextFieldlayer属性,我有以下代码:

    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;

I have kind of got it to work by making my UITextField extra long, so that the user does not see the left and right borders, but I was just wondering if there was a better, less hackish way of doing this?

我通过使我的 UITextField 超长来让它工作,这样用户就看不到左右边框,但我只是想知道是否有更好的,不那么hackish的方法来做到这一点?

I have checked the docs, and changing a UITextField's borderStyledoes not have this option.

我已经检查了文档,以及改变UITextFieldborderStyle不具有此选项。

From,

从,

An iOS First Timer

iOS 初学者

回答by user3075378

One approach I have found works good is using layers. Here's a snippet:

我发现一种很好的方法是使用层。这是一个片段:

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];

Hope this helps someone.

希望这可以帮助某人。

回答by Sebyddd

@user3075378's great & simple example in Swift

@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)

回答by Aviel Gross

@Sebyddd why stop there? (;

@Sebyddd 为什么停在那里?(;

EDIT:There is an issue with lines being drawn before auto layout sets the right frame for the view, I edited my answer with a fix: it basically involves calling drawLines()in layoutSubviews():

编辑:有一个与线的问题之前,自动布局设置视图右侧框架正在制定,我编辑我的答案与修复:它主要涉及调用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()
    }

}

回答by KDeogharkar

you can create one image that with top and bottom border and set it to the background of your UITextField :

您可以创建一张带有顶部和底部边框的图像并将其设置为 UITextField 的背景:

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

回答by Sarah Nguyen

You can also add views to the top and bottom to use as borders.

您还可以将视图添加到顶部和底部以用作边框。

// 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];

回答by Eli Burke

You can use layers to add lines / shapes to any UIView subclass. This code draws two lines at the top and bottom of a text field. You can add it to a subclass of a control, or call this directly in a parent view / view controller.

您可以使用图层向任何 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];

回答by kurtanamo

Swift 3: Clean with AutoLayout (I'm using here PureLayout but you can also do it with common NSLayoutConstraint:

Swift 3: Clean with 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)
}

回答by Doon

I will suggest you put one view on the left side of the textfield and one view on the right side of the textfield to cover the left/right border.

我建议您在文本字段的左侧放置一个视图,在文本字段的右侧放置一个视图以覆盖左/右边框。

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)];

回答by Travis Delly

Hope this helps, put this inside a textfield override class

希望这有帮助,把它放在一个文本字段覆盖类中

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]];

回答by hasan

Thanks to user3075378. my answer is based on his. adding right and left small lines.

感谢用户 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];
}