ios 如何在 UIButton 中创建边框?

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

How to create border in UIButton?

iosobjective-c

提问by iPhone

I use custom button in my app named "addButton" and I want to border it with white color how can i get the white color border around my custom button?

我在我的应用程序中使用名为“addButton”的自定义按钮,并且我想用白色将其边框化,我怎样才能在我的自定义按钮周围获得白色边框?

回答by bryanmac

You can set the border properties on the CALayer by accessing the layer property of the button.

您可以通过访问按钮的图层属性来设置 CALayer 上的边框属性。

First, add Quartz

首先,添加石英

#import <QuartzCore/QuartzCore.h>

Set properties:

设置属性:

myButton.layer.borderWidth = 2.0f;
myButton.layer.borderColor = [UIColor greenColor].CGColor;

See:

看:

https://developer.apple.com/documentation/quartzcore/calayer#//apple_ref/occ/cl/CALayer

https://developer.apple.com/documentation/quartzcore/calayer#//apple_ref/occ/cl/CALayer

The CALayer in the link above allows you to set other properties like corner radius, maskToBounds etc...

上面链接中的 CALayer 允许您设置其他属性,例如角半径、maskToBounds 等...

Also, a good article on button fun:

此外,还有一篇关于按钮乐趣的好文章:

https://web.archive.org/web/20161221132308/http://www.apptite.be/tutorial_custom_uibuttons.php

https://web.archive.org/web/20161221132308/http://www.apptite.be/tutorial_custom_uibuttons.php

回答by Ajeet Pratap Maurya

Its very simple, just add the quartzCore header in your file(for that you have to add the quartz framework to your project)

它非常简单,只需在您的文件中添加quartzCore 头文件(为此您必须将quartz 框架添加到您的项目中)

and then do this

然后这样做

[[button layer] setCornerRadius:8.0f];

[[button layer] setMasksToBounds:YES];

[[button layer] setBorderWidth:1.0f];

you can change the float values as required.

您可以根据需要更改浮点值。

enjoy.

请享用。



Here's some typical modern code ...

这是一些典型的现代代码......

self.buttonTag.layer.borderWidth = 1.0f;
self.buttonCancel.layer.borderWidth = 1.0f;

self.buttonTag.layer.borderColor = [UIColor blueColor].CGColor;
self.buttonCancel.layer.borderColor = [UIColor blueColor].CGColor;

self.buttonTag.layer.cornerRadius = 4.0f;
self.buttonCancel.layer.cornerRadius = 4.0f;

that's a similar look to segmented controls.

这与分段控件的外观相似。

UPDATE for Swift:

斯威夫特更新:

  • No need to add "QuartzCore"
  • 无需添加“QuartzCore”

Just do:

做就是了:

button.layer.cornerRadius = 8.0
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.black.cgColor

回答by tong

And in swift, you don't need to import "QuartzCore/QuartzCore.h"

并且在 swift 中,您不需要导入“QuartzCore/QuartzCore.h”

Just use:

只需使用:

button.layer.borderWidth = 0.8
button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor

or

或者

button.layer.borderWidth = 0.8
button.layer.borderColor = UIColor.grayColor().cgColor

回答by juanjo

The problem setting the layer's borderWidthand borderColoris that the when you touch the button the border doesn't animate the highlight effect.

问题设置图层的borderWidthborderColor是,当你触摸按钮的边框没有设置动画的高光效果。

Of course, you can observe the button's events and change the border color accordingly but that feels unnecessary.

当然,您可以观察按钮的事件并相应地更改边框颜色,但这感觉没有必要。

Another option is to create a stretchable UIImage and setting it as the button's background image. You can create an Image set in your Images.xcassets like this:

另一种选择是创建一个可拉伸的 UIImage 并将其设置为按钮的背景图像。您可以在您的 Images.xcassets 中创建一个图像集,如下所示:

Images.xcassets

图像.xcassets

Then, you set it as the button's background image:

然后,将其设置为按钮的背景图像:

Button properties

按钮属性

If your image is a template image you can set tint color of the button and the border will change:

如果您的图像是模板图像,您可以设置按钮的色调颜色,边框将发生变化:

Final Button

最终按钮

Now the border will highlight with the rest of the button when touched.

现在,触摸时边框将与按钮的其余部分一起突出显示。

回答by Alex

To change button Radius, Color and Width I set like this:

要更改按钮半径、颜色和宽度,我设置如下:

self.myBtn.layer.cornerRadius = 10;
self.myBtn.layer.borderWidth = 1;
self.myBtn.layer.borderColor =[UIColor colorWithRed:189.0/255.0f green:189.0/255.0f blue:189.0/255.0f alpha:1.0].CGColor;

回答by LaloLoop

Here's an updated version (Swift 3.0.1) from Ben Packard's answer.

这是Ben Packard回答的更新版本 ( Swift 3.0.1) 。

import UIKit

@IBDesignable class BorderedButton: UIButton {

    @IBInspectable var borderColor: UIColor? {
        didSet {
            if let bColor = borderColor {
                self.layer.borderColor = bColor.cgColor
            }
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            self.layer.borderWidth = borderWidth
        }
    }

    override var isHighlighted: Bool {
        didSet {
            guard let currentBorderColor = borderColor else {
                return
            }

            let fadedColor = currentBorderColor.withAlphaComponent(0.2).cgColor

            if isHighlighted {
                layer.borderColor = fadedColor
            } else {

                self.layer.borderColor = currentBorderColor.cgColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = currentBorderColor.cgColor
                animation.duration = 0.4
                self.layer.add(animation, forKey: "")
            }
        }
    }
}

The resulting button can be used inside your StoryBoard thanks to the @IBDesignableand @IBInspectabletags.

由于@IBDesignable@IBInspectable标签,生成的按钮可以在您的 StoryBoard 中使用。

enter image description here

在此处输入图片说明

Also the two properties defined, allow you to set the border width and color directly on interface builder and preview the result.

还定义了两个属性,允许您直接在界面构建器上设置边框宽度和颜色并预览结果。

enter image description here

在此处输入图片说明

Other properties could be added in a similar fashion, for border radius and highlight fading time.

可以以类似的方式添加其他属性,用于边框半径和高光衰落时间。

回答by BHUVANESH MOHANKUMAR

This can be achieved in various methods in Swift 3.0 Worked on Latest version August - 2017

这可以通过 Swift 3.0 中的各种方法实现 最新版本 2017 年 8 月

Option 1:

选项1:

Directly assign the borderWidth property values for UI Button:

直接为 UI Button 分配 borderWidth 属性值:

  btnUserButtonName.layer.borderWidth = 1.0

Set Title with Default Color values for UI Button:

使用 UI 按钮的默认颜色值设置标题:

btnUserButtonName.setTitleColor(UIColor.darkGray, for: .normal)

Set Border with Default Color for the border property values for UI Button:

使用默认颜色为 UI 按钮的边框属性值设置边框:

btnUserButtonName.layer.borderColor = UIColor.red

Set user defined Color for the border property values for UI Button:

为 UI 按钮的边框属性值设置用户定义的颜色:

   let myGrayColor = UIColor(red: 0.889415, green: 0.889436, blue:0.889424, alpha: 1.0 )
   btnUserButtonName.layer.borderColor = myGrayColor.cgColor

Option 2: [Recommended]

选项 2:[推荐]

Use the Extension method, so the Button through out the application will be looking consistent and no need to repeat multiple lines of code every where.

使用 Extension 方法,因此整个应用程序中的 Button 将看起来一致,无需在任何地方重复多行代码。

//Create an extension class in any of the swift file

extension UIButton {
func setBordersSettings() {
        let c1GreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 5.0
        self.layer.borderColor = c1GreenColor.cgColor
        self.setTitleColor(c1GreenColor, for: .normal)
        self.layer.masksToBounds = true
    }
}

Usage in code:

代码中的用法:

//use the method and call whever the border has to be applied

btnUserButtonName.setBordersSettings()

Output of Extension method Button:

扩展方法按钮的输出:

enter image description here

在此处输入图片说明

回答by Ben Packard

Here's a UIButtonsubclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.

这是一个UIButton支持高亮状态动画而不使用图像的子类。当视图的色调模式改变时,它也会更新边框颜色。

class BorderedButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = tintColor.CGColor
        layer.borderWidth = 1
        layer.cornerRadius = 5

        contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        layer.borderColor = tintColor.CGColor
    }

    override var highlighted: Bool {
        didSet {
            let fadedColor = tintColor.colorWithAlphaComponent(0.2).CGColor

            if highlighted {
                layer.borderColor = fadedColor
            } else {
                layer.borderColor = tintColor.CGColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = tintColor.CGColor
                animation.duration = 0.4
                layer.addAnimation(animation, forKey: "")
            }
        }
    }
}

Usage:

用法:

let button = BorderedButton(style: .System) //style .System is important

let button = BorderedButton(style: .System) //style .System is important

Appearance:

外貌:

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

回答by Vinay Jain

You don't need to import QuartzCore.hnow. Taking iOS 8 sdk and Xcode 6.1 in referrence.

您现在不需要导入QuartzCore.h。以 iOS 8 sdk 和 Xcode 6.1 为参考。

Directly use:

直接使用:

[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];

回答by Raj Joshi

Update with Swift 3

使用 Swift 3 更新

    button.layer.borderWidth = 0.8
    button.layer.borderColor = UIColor.blue.cgColor

enter image description here

在此处输入图片说明