ios 如何在 UIButton 上仅添加顶部边框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19890956/
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-31 02:50:04  来源:igfitidea点击:

How to add only a TOP border on a UIButton?

iosiphonecocoa-touchuibuttonios7

提问by Erzékiel

I know how to add border to a button in iOS 7, with the following code :

我知道如何使用以下代码为 iOS 7 中的按钮添加边框:

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

But how can I add just one border ? I want to add only the top border.

但是我怎样才能只添加一个边框呢?我只想添加顶部边框

回答by masgar

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

you can do the same for each border. Adding multiple UIViews you can add bottom and left or top and right or any border you want.

你可以对每个边框做同样的事情。添加多个 UIViews 您可以添加底部和左侧或顶部和右侧或您想要的任何边框。

i.e. bottom & left:

即底部和左侧:

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

if you don't use ARC, remember to release UIViews after adding subviews (or use autorelease).

如果你不使用ARC,记得在添加子视图后释放UIViews(或者使用autorelease)。

回答by peacetype

Here is masgar's solution implemented in Swift:

这是 masgar 在 Swift 中实现的解决方案:

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

回答by Kiran P Nair

In Swift add an extension for UIView class like this:

在 Swift 中为 UIView 类添加一个扩展,如下所示:

Swift 3 *

斯威夫特 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)
}
}

I got this extension from this link:UIView bottom border?

我从这个链接得到了这个扩展:UIView bottom border?

Then call the function like this

然后像这样调用函数

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

For adaptive layout use this one

对于自适应布局使用这个

Swift 3

斯威夫特 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))
}
}

Usage:

用法:

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

回答by Barath

Swift 4

斯威夫特 4

UIButton Top Border

UIButton 顶部边框

var lineView = UIView(frame: CGRect(x: 0, y: 0, width: button.frame.size.width, height: 2))
lineView.backgroundColor= UIColor.black
button.addSubview(lineView)

UIButton Bottom Border

UIButton 底部边框

var lineView = UIView(frame: CGRect(x: 0, y: button.frame.size.height, width: button.frame.size.width, height: 2))
lineView.backgroundColor= UIColor.black
button.addSubview(lineView)

回答by Danyun Liu

Just draw the border yourself:

自己画边框:

@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

回答by long vv

Actually I meet this questions as you,but I think my method is better than the answer which you choose. You should create a class inherit the UIControl like UIButton.

其实我和你一样遇到这个问题,但我认为我的方法比你选择的答案更好。您应该创建一个类继承 UIControl 像 UIButton。

@interface customButton : UIButton

and rewrite the drawrect method like this:

并像这样重写 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);

}

}

By the way~ your purpose UIControl should use your class in xib's setting

顺便说一句~你的目的 UIControl 应该在 xib 的设置中使用你的类

this setting

这个设置

Last~ show you my custom UIButton. I think we should choose this method and combine UIBezierPath's API to finish our demand.

最后~给你看看我的自定义 UIButton。我觉得我们应该选择这种方式,结合 UIBezierPath 的 API 来完成我们的需求。

enter image description here

enter image description here

Thank you for watching~ hope to study and discuss together~ From a iOS fisherman -- vvlong

谢谢收看~希望一起学习讨论~来自一个iOS渔民——vvlong

回答by Andrea

You can't using this layer methods.
The best solution here is create a small image (by code or photoshop), use the - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingModeto resize it according to the aspect that you want give and add it as a background image. This is really a good approach because it helps you to keep a very small memory footprint and that adapts your image to all button sizes.
Here a good tutorial.

您不能使用此图层方法。
这里最好的解决方案是创建一个小图像(通过代码或 photoshop),使用 -(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode根据您想要的方面调整其大小并将其添加为背景图像。这确实是一个很好的方法,因为它可以帮助您保持非常小的内存占用,并使您的图像适应所有按钮大小。
这里有一个很好的教程

回答by Inti

If you use constraints then you can add a border view with the required constraints

如果使用约束,则可以添加具有所需约束的边框视图

// MARK: - Add a border to one side of a view

public enum BorderSide {
    case top, bottom, left, right
}

extension UIView {
    public func addBorder(side: BorderSide, color: UIColor, width: CGFloat) {
        let border = UIView()
        border.translatesAutoresizingMaskIntoConstraints = false
        border.backgroundColor = color
        self.addSubview(border)

        let topConstraint = topAnchor.constraint(equalTo: border.topAnchor)
        let rightConstraint = trailingAnchor.constraint(equalTo: border.trailingAnchor)
        let bottomConstraint = bottomAnchor.constraint(equalTo: border.bottomAnchor)
        let leftConstraint = leadingAnchor.constraint(equalTo: border.leadingAnchor)
        let heightConstraint = border.heightAnchor.constraint(equalToConstant: width)
        let widthConstraint = border.widthAnchor.constraint(equalToConstant: width)


        switch side {
        case .top:
            NSLayoutConstraint.activate([leftConstraint, topConstraint, rightConstraint, heightConstraint])
        case .right:
            NSLayoutConstraint.activate([topConstraint, rightConstraint, bottomConstraint, widthConstraint])
        case .bottom:
            NSLayoutConstraint.activate([rightConstraint, bottomConstraint, leftConstraint, heightConstraint])
        case .left:
            NSLayoutConstraint.activate([bottomConstraint, leftConstraint, topConstraint, widthConstraint])
        }
    }
}

Then set it something like the below

然后将其设置为如下所示

myButton.addBorder(side: .left, color: UIColor.lightGray, width: 1)

(inspired by this answer)

(受到这个答案的启发)

回答by Kevin

You have to create a new layer or view 1pt high, set its background color to the color you want your border, and add it as a subview/sublayer.

您必须创建一个新图层或视图 1pt 高,将其背景颜色设置为您想要边框的颜色,并将其添加为子视图/子图层。

回答by Maxthon Chan

If you need anything other than the default, you need to manually draw it.

如果您需要除默认值以外的任何内容,则需要手动绘制它。