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

Как добавить только верхнюю границу на UIButton?

Я знаю, как добавить границу к кнопке в iOS 7 со следующим кодом:

[[myButton layer] setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
[[myButton layer] setBorderWidth:1];
[[myButton layer] setCornerRadius:15];

Но как я могу добавить только одну границу? Я хочу добавить только верхнюю границу.

4b9b3361

Ответ 1

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, btn.frame.size.width, 1)];
lineView.backgroundColor = [UIColor redColor];
[btn addSubview:lineView];

вы можете сделать то же самое для каждой границы. Добавляя несколько UIViews, вы можете добавлять нижние и левые, верхние и правые или любые границы, которые вы хотите.

то есть. внизу и слева:

UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, btn.frame.size.height - 1.0f, btn.frame.size.width, 1)];
bottomBorder.backgroundColor = [UIColor redColor];

UIView *leftBorder = [[UIView alloc] initWithFrame:CGRectMake(1, 0, 1, btn.frame.size.height)];
leftBorder.backgroundColor = [UIColor redColor];

[btn addSubview:bottomBorder];
[btn addSubview:leftBorder];

если вы не используете ARC, не забудьте освободить UIViews после добавления subviews (или использовать autorelease).

Ответ 2

Вот решение masgar, реализованное в Swift:

    var lineView = UIView(frame: CGRectMake(0, 0, btn.frame.size.width, 1))
    lineView.backgroundColor=UIColor.redColor()
    btn.addSubview(lineView)

Ответ 3

В Swift добавьте расширение для класса UIView следующим образом:

Swift 2 *

import Foundation
import UIKit
extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.CGColor
    border.frame = CGRectMake(0, 0, self.frame.size.width, width)
    self.layer.addSublayer(border)
}

func addRightBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.CGColor
    border.frame = CGRectMake(self.frame.size.width - width, 0, width, self.frame.size.height)
    self.layer.addSublayer(border)
}

func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.CGColor
    border.frame = CGRectMake(0, self.frame.size.height - width, self.frame.size.width, width)
    self.layer.addSublayer(border)
}

func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.CGColor
    border.frame = CGRectMake(0, 0, width, self.frame.size.height)
    self.layer.addSublayer(border)
}

}

Swift 3 *

extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x:0,y: 0, width:self.frame.size.width, height:width)
    self.layer.addSublayer(border)
}

func addRightBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: self.frame.size.width - width,y: 0, width:width, height:self.frame.size.height)
    self.layer.addSublayer(border)
}

func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x:0, y:self.frame.size.height - width, width:self.frame.size.width, height:width)
    self.layer.addSublayer(border)
}

func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
    let border = CALayer()
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x:0, y:0, width:width, height:self.frame.size.height)
    self.layer.addSublayer(border)
}
}

Я получил это расширение из этой ссылки: нижняя граница UIView?

Затем вызовите функцию, подобную этой

var innerView : UIView?
    let borderWidth: CGFloat = 1.0
    let borderColor : UIColor =  UIColor.redColor()
    innerView!.addTopBorderWithColor(borderColor, width: borderWidth)

Для адаптивного макета используйте этот Swift 2.

extension UIView {   

func addTopBorder(color: UIColor, height: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Height,
        relatedBy: NSLayoutRelation.Equal,
        toItem: nil,
        attribute: NSLayoutAttribute.Height,
        multiplier: 1, constant: height))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Top,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Top,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Leading,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Leading,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Trailing,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Trailing,
        multiplier: 1, constant: 0))
}

func addBottomBorder(color: UIColor, height: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Height,
        relatedBy: NSLayoutRelation.Equal,
        toItem: nil,
        attribute: NSLayoutAttribute.Height,
        multiplier: 1, constant: height))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Bottom,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Bottom,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Leading,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Leading,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Trailing,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Trailing,
        multiplier: 1, constant: 0))
}
func addLeftBorder(color: UIColor, width: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Width,
        relatedBy: NSLayoutRelation.Equal,
        toItem: nil,
        attribute: NSLayoutAttribute.Width,
        multiplier: 1, constant: width))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Leading,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Leading,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Bottom,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Bottom,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Top,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Top,
        multiplier: 1, constant: 0))
}
func addRightBorder(color: UIColor, width: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Width,
        relatedBy: NSLayoutRelation.Equal,
        toItem: nil,
        attribute: NSLayoutAttribute.Width,
        multiplier: 1, constant: width))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Trailing,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Trailing,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Bottom,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Bottom,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.Top,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.Top,
        multiplier: 1, constant: 0))
}

}

button!.addTopBorder(UIColor(red: 247.0/255.0, green: 147.0/255.0, blue: 29.0/255.0, alpha: 0.5), height: borderWidth)

Swift 3

extension UIView {

func addTopBorder(_ color: UIColor, height: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.height,
        relatedBy: NSLayoutRelation.equal,
        toItem: nil,
        attribute: NSLayoutAttribute.height,
        multiplier: 1, constant: height))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.top,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.top,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.leading,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.leading,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.trailing,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.trailing,
        multiplier: 1, constant: 0))
}

func addBottomBorder(_ color: UIColor, height: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.height,
        relatedBy: NSLayoutRelation.equal,
        toItem: nil,
        attribute: NSLayoutAttribute.height,
        multiplier: 1, constant: height))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.bottom,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.bottom,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.leading,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.leading,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.trailing,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.trailing,
        multiplier: 1, constant: 0))
}
func addLeftBorder(_ color: UIColor, width: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.width,
        relatedBy: NSLayoutRelation.equal,
        toItem: nil,
        attribute: NSLayoutAttribute.width,
        multiplier: 1, constant: width))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.leading,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.leading,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.bottom,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.bottom,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.top,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.top,
        multiplier: 1, constant: 0))
}
func addRightBorder(_ color: UIColor, width: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(border)
    border.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.width,
        relatedBy: NSLayoutRelation.equal,
        toItem: nil,
        attribute: NSLayoutAttribute.width,
        multiplier: 1, constant: width))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.trailing,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.trailing,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.bottom,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.bottom,
        multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: border,
        attribute: NSLayoutAttribute.top,
        relatedBy: NSLayoutRelation.equal,
        toItem: self,
        attribute: NSLayoutAttribute.top,
        multiplier: 1, constant: 0))
}
}

Использование:

button!.addTopBorder(UIColor(red: 247.0/255.0, green: 147.0/255.0, blue: 29.0/255.0, alpha: 0.5), height: borderWidth)

Ответ 4

Просто нарисуйте границу самостоятельно:

@implementation TopBorderButton
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    CGContextFillRect(context, CGRectMake(0.0f, 0.0, self.frame.size.width, 1.0));
}
@end

Ответ 5

Вы не можете использовать эти методы слоя.
Лучшее решение здесь - создать небольшое изображение (по коду или фотошопу), используйте - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode, чтобы изменить его размер в соответствии с аспектом, который вы хотите дать, и добавьте его в качестве фонового изображения. Это действительно хороший подход, поскольку он помогает сохранить очень небольшой объем памяти и адаптирует ваше изображение ко всем размерам кнопок.
Вот хороший учебник.

Ответ 6

На самом деле я встречаю эти вопросы, как вы, но я думаю, что мой метод лучше, чем тот, который вы выберете. Вы должны создать класс, наследующий UIControl как UIButton.

@interface customButton : UIButton

и перепишите метод drawrect следующим образом:

- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 1.5);  //线宽
CGContextSetAllowsAntialiasing(context, true);
CGContextSetRGBStrokeColor(context, 193/255.0, 205/255.0, 193/255.0, 1.0);  //线的颜色
CGContextBeginPath(context);

CGContextMoveToPoint(context, 0, 0);  //起点坐标
CGContextAddLineToPoint(context, self.frame.size.width, 0);   //终点坐标

CGContextStrokePath(context);

}

Кстати, ваша цель UIControl должна использовать ваш класс в настройке xib

этот параметр

Last ~ показать вам свой пользовательский UIButton. Я думаю, что мы должны выбрать этот метод и объединить API UIBezierPath, чтобы удовлетворить наш спрос.

введите описание изображения здесь

Спасибо, что посмотрели ~ надеюсь учиться и обсуждать вместе ~                                      От рыбака iOS - vvlong

Ответ 7

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

Ответ 8

Если вам нужно что-то другое, кроме значения по умолчанию, вам нужно вручную нарисовать его.

Ответ 9

Лучший и простой способ....

btnTest.selectiveBorderFlag = AUISelectiveBordersFlagBottom | AUISelectiveBordersFlagTop;
btnTest.selectiveBordersColor = [UIColor redColor];
btnTest.selectiveBordersWidth = 3.0;

Использовали ли они это: этот открытый исходный код