Нарисуйте только верхнюю, правую и нижнюю границы вокруг uilabel

Я пытаюсь добавить границу для uilabel, но я хочу иметь границу top, right, and bottom.

как это

           ----------------
                          |
            I am a label  |
                          |
           ----------------

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

    myLabel.layer.borderWidth = 1;
    myLabel.layer.borderColor = [UIColor blackColor];

Это так или иначе, я могу добавить только 3 стороны или даже 1 или 2 стороны?

Спасибо!

Ответы

Ответ 1

Вы можете использовать маску. Это код, который я использовал для проверки теории, и он хорошо работает:

// Define the border width in a variable, we'll be using it elsewhere
CGFloat borderWidth = 1.0;

// This creates a testing view to test the theory, in your case this will be your UILabel
UIView* view = [[UIView alloc] initWithFrame:CGRectMake(20, 60, 250, 100)];
view.layer.borderColor = [UIColor blackColor].CGColor;
view.layer.borderWidth = borderWidth;
[self.view addSubview:view];

// Create the mask to cover the area of the view you want to **show**
// Here, we create a mask that covers most of the view, except the left edge
// The mask needs to be coloured in black, as black acts as transparent, whereas white is opaque in mask parlance
UIView* mask = [[UIView alloc] initWithFrame:CGRectMake(borderWidth, 0, view.frame.size.width - borderWidth, view.frame.size.height)];
mask.backgroundColor = [UIColor blackColor];
view.layer.mask = mask.layer;

Вы можете настроить размер и положение маски (с учетом borderWidth), чтобы показать/скрыть граничные границы, которые вас интересуют. Пример выше скрывает левый край.

Ответ 2

Вам придется настраивать размеры, но это суть. (могут быть некоторые опечатки)

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 35)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 320, 20)];

CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0, 40, 320, .5);

CALayer *rightBorder = [CALayer layer];
rightBorder.frame = CGRectMake(320, 0, 40, .5);

CALayer *topBorder = [CALayer layer];
topBorder.frame = CGRectMake(0, 0, 320, .5);

[view.layer addSublayer:bottomBorder];
[view.layer addSublayer:topBorder];
[view.layer addSublayer:rightBorder];
[view.layer addSublayer:label];

Ответ 3

Вы можете нарисовать свои три стороны одной строкой, создав CALayer, который использует UIBezierPath. Со всеми примерами включите среду QuartzCore как часть вашего проекта.

После исходного кода в качестве отправной точки:

// at the top of the file with this code, include:
#import <QuartzCore/QuartzCore.h>

CGRect rect = myLabel.frame;

UIBezierPath * linePath = [UIBezierPath bezierPath];

// start at top left corner
[linePath moveToPoint:CGPointMake(0,0);
// draw top line across
[linePath addLineToPoint:CGPointMake(rect.size.width, 0);
// draw right vertical side
[linePath addLineToPoint:CGPointMake(rect.size.width, rect.size.height);
// draw left vertical side
[linePath addLineToPoint:CGPointMake(0, rect.size.height);

// draw from bottom right corner back to bottom left corner
[linePath addLineToPoint:CGPointMake(0, rect.size.height);

// create a layer that uses your defined path
CAShapeLayer * lineLayer = [CAShapeLayer layer];
lineLayer.lineWidth = 1.0;
lineLayer.strokeColor = [UIColor blackColor].CGColor;

lineLayer.fillColor = nil;
lineLayer.path = linePath.CGPath;

[myLabel.layer addSublayer:lineLayer];

Ответ 4

Я использую Swift 3.

// myLabel is a UILabel
let frame = myLabel.frame //Frame of label

// Bottom Layer
let bottomLayer = CALayer()
bottomLayer.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width, height: 1)
bottomLayer.backgroundColor = UIColor.black.cgColor
myLabel.layer.addSublayer(bottomLayer)

// Top Layer
let topLayer = CALayer()
topLayer.frame = CGRect(x: 0, y: 0, width: frame.width, height: 1)
topLayer.backgroundColor = UIColor.black.cgColor
myLabel.layer.addSublayer(topLayer)

Аналогично:

// Right Layer
let rightLayer = CALayer()
rightLayer.frame = CGRect(x: frame.width - 1, y: 0, width: 1, height: frame.height)
rightLayer.backgroundColor = UIColor.black.cgColor
myLabel.layer.addSublayer(rightLayer)

Где 1 - ширина границы.

Ответ 5

Здесь вы, ребята, уходите! Надеюсь, что это поможет, добавьте это внутри класса переопределения UItextfield

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

Ответ 6

Вы можете подклассифицировать UILabel и переопределить drawRect: для этого.

Или вы можете просто сделать 3 UIView с черным фоном в качестве подзонов этой метки. Если вы правильно установите для них autooresizingMask, они приступят к изменениям в размере метки. Верхняя граница должна иметь гибкую ширину и гибкое нижнее поле, нижняя граница должна иметь гибкую ширину и гибкий верхний край, правая граница должна иметь гибкую высоту и гибкое левое поле.

Ответ 7

Вы можете сделать это несколькими способами: Первый - самый простой, просто найдите изображение, похожее на штрихи на границе. Затем добавьте UIImageView обратно в UILabel. Второй способ переопределяет UILabel drawRect: затем нарисуйте сток в соответствии с вашими потребностями.