如何在Swift中使按钮具有圆形边框?

时间:2014-11-16 17:07:50

标签: swift uibutton

我在最新版本的Xcode 6中使用swift构建应用程序,并想知道如何修改我的按钮,以便它可以有一个圆形边框,我可以根据需要调整自己。完成后,如何在不添加背景的情况下更改边框的颜色?换句话说,我想要一个没有背景的略微圆角的按钮,只有一个特定颜色的1pt边框。

15 个答案:

答案 0 :(得分:451)

使用button.layer.cornerRadiusbutton.layer.borderColorbutton.layer.borderWidth。 请注意,borderColor需要CGColor,所以你可以说(Swift 3/4):

button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor

答案 1 :(得分:40)

在故事板(Interface Builder Inspector)中执行此作业

借助IBDesignable,我们可以为UIButton的Interface Builder Inspector添加更多选项,并在故事板上进行调整。首先,将以下代码添加到项目中。

@IBDesignable extension UIButton {

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }
}

然后只需在故事板上设置按钮的属性。

enter image description here

答案 2 :(得分:13)

本课程基于答案中的所有评论和建议,也可以直接从xcode设计。复制到您的项目并插入任何UIButton并更改为使用自定义类,现在只需从xcode中选择正常和/或突出显示状态的边框或背景颜色。

//
//  RoundedButton.swift
//

import UIKit

@IBDesignable
class RoundedButton:UIButton {

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }
    //Normal state bg and border
    @IBInspectable var normalBorderColor: UIColor? {
        didSet {
            layer.borderColor = normalBorderColor?.CGColor
        }
    }

    @IBInspectable var normalBackgroundColor: UIColor? {
        didSet {
            setBgColorForState(normalBackgroundColor, forState: .Normal)
        }
    }


    //Highlighted state bg and border
    @IBInspectable var highlightedBorderColor: UIColor?

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        didSet {
            setBgColorForState(highlightedBackgroundColor, forState: .Highlighted)
        }
    }


    private func setBgColorForState(color: UIColor?, forState: UIControlState){
        if color != nil {
            setBackgroundImage(UIImage.imageWithColor(color!), forState: forState)

        } else {
            setBackgroundImage(nil, forState: forState)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        layer.cornerRadius = layer.frame.height / 2
        clipsToBounds = true

        if borderWidth > 0 {
            if state == .Normal && !CGColorEqualToColor(layer.borderColor, normalBorderColor?.CGColor) {
                layer.borderColor = normalBorderColor?.CGColor
            } else if state == .Highlighted && highlightedBorderColor != nil{
                layer.borderColor = highlightedBorderColor!.CGColor
            }
        }
    }

}

//Extension Required by RoundedButton to create UIImage from UIColor
extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect: CGRect = CGRectMake(0, 0, 1, 1)
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), false, 1.0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

答案 3 :(得分:8)

根据@returntrue的回答,我设法在Interface Builder中实现它。

要使用Interface Builder获取圆角按钮,请在" Path = "layer.cornerRadius"&中添加一个键Type = "Number",其中包含Value = "10"User Defined RunTime Attribute(或其他所需值) #34;按钮的Identity Inspector

答案 4 :(得分:3)

我认为最简单,最干净的方法是使用协议来避免继承和代码重复。 您可以直接从故事板

更改此属性
protocol Traceable {
    var cornerRadius: CGFloat { get set }
    var borderColor: UIColor? { get set }
    var borderWidth: CGFloat { get set }
}

extension UIView: Traceable {

    @IBInspectable var cornerRadius: CGFloat {
        get { return layer.cornerRadius }
        set {
            layer.masksToBounds = true
            layer.cornerRadius = newValue
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            guard let cgColor = layer.borderColor else { return nil }
            return  UIColor(cgColor: cgColor)
        }
        set { layer.borderColor = newValue?.cgColor }
    }

    @IBInspectable var borderWidth: CGFloat {
        get { return layer.borderWidth }
        set { layer.borderWidth = newValue }
    }
}

更新

在此link中,您可以找到一个使用Traceable协议实用程序的示例

enter image description here

答案 5 :(得分:2)

您可以使用UIButton的这个子类根据您的需要自定义UIButton。

visit this github repo for reference

import UIKit

var str = "Hello, playground"

class QueueManager {

    typealias FunctionType = () -> ()

    private var functions = [(String, FunctionType)]()

    func add(funcName: String, function: @escaping FunctionType) -> QueueManager {
        functions.append((funcName, function))
        return self
    }

    func runFirst() -> Bool {
        guard functions.isEmpty == false else { return false }
        print(functions)
        functions.first!.1()
        functions.removeFirst()
        return true
    }
}

var value = 1
let queueManager = QueueManager()

func simpleFunction(_ value: AnyObject){
    print(value)
}

queueManager.add(funcName: "simpleFunction"){
    simpleFunction(value as AnyObject)
}

queueManager.add(funcName: "simpleFunction"){
    value = 2
    simpleFunction(value as AnyObject)
}

queueManager.runFirst()
queueManager.runFirst()

答案 6 :(得分:2)

   @IBOutlet weak var yourButton: UIButton! {
        didSet{
            yourButton.backgroundColor = .clear
            yourButton.layer.cornerRadius = 10
            yourButton.layer.borderWidth = 2
            yourButton.layer.borderColor = UIColor.white.cgColor
        }
    }

答案 7 :(得分:1)

import UIKit

@IBDesignable
class RoundedButton: UIButton {
    
    @IBInspectable var cornerRadius: CGFloat = 8
    @IBInspectable var borderColor: UIColor? = .lightGray
    
    override func draw(_ rect: CGRect) {
        layer.cornerRadius = cornerRadius
        layer.masksToBounds = true
        layer.borderWidth = 1
        layer.borderColor = borderColor?.cgColor
        
    }
    
    
}

答案 8 :(得分:0)

@IBOutlet weak var button: UIButton!

...

我认为对于半径来说这个参数足够了:

button.layer.cornerRadius = 5

答案 9 :(得分:0)

除了提示之外,请确保您的按钮不是故事板中任何自定义类的子类,在这种情况下,您的代码最佳位置应该在自定义类中,如果您的按钮是子类,则自行导致代码只能在自定义类中工作默认的UIButton类和它的出口,希望这可以帮助任何人想知道为什么角落无线电不适用于我的按钮代码。

答案 10 :(得分:0)

尝试 带有圆角的按钮边框

anyButton.backgroundColor = .clear

anyButton.layer.cornerRadius = anyButton.frame.height / 2

anyButton.layer.borderWidth = 1

anyButton.layer.borderColor = UIColor.black.cgColor

答案 11 :(得分:0)

我认为这是简单的形式

        Button1.layer.cornerRadius = 10(Half of the length and width)
        Button1.layer.borderWidth = 2

答案 12 :(得分:0)

这是UIButton圆角边框的全局方法

class func setRoundedBorderButton(btn:UIButton)
{
   btn.layer.cornerRadius = btn.frame.size.height/2
   btn.layer.borderWidth = 0.5
   btn.layer.borderColor = UIColor.darkGray.cgColor
}

答案 13 :(得分:0)

UIBuilder 爱好者的解决方案:

  1. 在 UIButton 的“Attribution Inspector”窗口中选中“Clip to Bounds”复选框。 [见下图1]

  2. 点击“Identity Inspector”,然后点击“+”符号输入一个新的关键路径:layer.cornerRadius、Number、8(或16等...)。 [见下图2]

图 1:裁剪到边界复选框 Figure 1: Clip to Bounds check box

图 2:关键路径代码... Figure 2: Key Path code

图 3:生成的图像按钮 Figure 3: the resultant image-button

答案 14 :(得分:-1)

您可以将UIButton子类化并添加@IBInspectable变量,以便您可以通过StoryBoard"属性检查器"配置自定义按钮参数。下面我写下那段代码。

@IBDesignable
class BHButton: UIButton {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    @IBInspectable lazy var isRoundRectButton : Bool = false

    @IBInspectable public var cornerRadius : CGFloat = 0.0 {
        didSet{
            setUpView()
        }
    }

    @IBInspectable public var borderColor : UIColor = UIColor.clear {
        didSet {
            self.layer.borderColor = borderColor.cgColor
        }
    }

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

    //  MARK:   Awake From Nib

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        if isRoundRectButton {
            self.layer.cornerRadius = self.bounds.height/2;
            self.clipsToBounds = true
        }
        else{
            self.layer.cornerRadius = self.cornerRadius;
            self.clipsToBounds = true
        }
    }

}