У меня есть две метки, которые сложены. Если мне нужна горизонтальная линия между ними, есть ли другой способ помимо использования изображения с UIImageView?
Создание горизонтальной линии
Ответ 1
Создайте UIView с черным фоном, высотой 1 пиксель и шириной 320 пикселей.
Ответ 2
Используйте UIView:
UIView * separator = [[UIView alloc] initWithFrame:CGRectMake(x, y, 320, 1)];
separator.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1];
[self.view addSubview:separator];
[separator release];
Ответ 3
В то время как решение Jasarien красиво и просто, оно не создает фактическую 1-пиксельную линию волос, а 2-пиксельную линию на 2X устройствах.
Я нашел сообщение в блоге о том, как создать реальную тонкую линию волос 1 пиксель. Нам нужен подкласс UIView. Для Swift это будет:
import UIKit
class HairlineView: UIView {
override func awakeFromNib() {
guard let backgroundColor = self.backgroundColor?.CGColor else { return }
self.layer.borderColor = backgroundColor
self.layer.borderWidth = (1.0 / UIScreen.mainScreen().scale) / 2;
self.backgroundColor = UIColor.clearColor()
}
}
Ответ 4
Для горизонтальной линии
UIView *horizontalLine = [[UIView alloc]initWithFrame:CGRectMake(x cordinate,y cordinate,1,linelenth)];
horizontalLine.backgroundColor = [UIColor blackColor];
[self. view addSubView:horizontalLine];
[horizontalLine release];
Для вертикальной линии
UIView *verticalLine = [[UIView alloc]initWithFrame:CGRectMake(x cordinate,y cordinate,linelenth,1)];
verticalLine.backgroundColor = [UIColor blackColor];
[self. view addSubView:verticalLine];
[verticalLine release];
Ответ 5
Попробуй это
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case .top:
border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
case .bottom:
border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
case .left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
case .right:
border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
default:
break
}
border.backgroundColor = color.cgColor;
addSublayer(border)
}
Ответ 6
Вы можете удалить это в UIView
- (void)drawRect:(CGRect)rect
{
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Shadow Declarations
CGColorRef outerShadow = [UIColor blackColor].CGColor;
CGSize outerShadowOffset = CGSizeMake(0, 1);
CGFloat outerShadowBlurRadius = 2;
//// Abstracted Graphic Attributes
CGRect rectangleFrame = CGRectMake(0, 0, self.frame.size.width, 3);
//// Rectangle Drawing
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: rectangleFrame];
[[UIColor lightGrayColor] setFill];
[rectanglePath fill];
////// Rectangle Inner Shadow
CGRect rectangleBorderRect = CGRectInset([rectanglePath bounds], -outerShadowBlurRadius, -outerShadowBlurRadius);
rectangleBorderRect = CGRectOffset(rectangleBorderRect, -outerShadowOffset.width, -outerShadowOffset.height);
rectangleBorderRect = CGRectInset(CGRectUnion(rectangleBorderRect, [rectanglePath bounds]), -1, -1);
UIBezierPath* rectangleNegativePath = [UIBezierPath bezierPathWithRect: rectangleBorderRect];
[rectangleNegativePath appendPath: rectanglePath];
rectangleNegativePath.usesEvenOddFillRule = YES;
CGContextSaveGState(context);
{
CGFloat xOffset = outerShadowOffset.width + round(rectangleBorderRect.size.width);
CGFloat yOffset = outerShadowOffset.height;
CGContextSetShadowWithColor(context,
CGSizeMake(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset)),
outerShadowBlurRadius,
outerShadow);
[rectanglePath addClip];
CGAffineTransform transform = CGAffineTransformMakeTranslation(-round(rectangleBorderRect.size.width), 0);
[rectangleNegativePath applyTransform: transform];
[[UIColor grayColor] setFill];
[rectangleNegativePath fill];
}
CGContextRestoreGState(context);
}
Ответ 7
Чтобы быстро создать линию с нуля, просто сделайте это
let line = UIView()
view.addSubview(line)
line.translatesAutoresizingMaskIntoConstraints = false
line.widthAnchor.constraint(equalToConstant: view.bounds.width - 40).isActive = true
line.heightAnchor.constraint(equalToConstant: 1).isActive = true
line.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
line.topAnchor.constraint(equalTo: userName.bottomAnchor,constant: 20).isActive = true
line.backgroundColor = .gray
Ширина линии равна ширине устройства - некоторая константа и эта же константа добавляются слева, поэтому мы получаем строку примерно так