簡體   English   中英

在 Storyboard 中為 UIButton 設置邊框

[英]Set a border for UIButton in Storyboard

如果不直接在代碼中設置它們,我就無法在 Xcode 5 中為我的按鈕設置邊框。 如果不制作自定義背景圖像,是否可能無法在情節提要上執行此操作?

您可以使用密鑰路徑。

例如圖像上描述的角半徑( layer.cornerRadius )。 您將無法看到情節提要上的效果,因為此參數是在運行時評估的。 現在,您可以在 UIView(圖片@IBInspectable代碼)中使用帶有@IBInspectable的 swift 類別以在故事板中顯示結果(如果您正在使用該類別,請僅使用cornerRadius而不是layer.cornerRadius作為關鍵路徑。

在此處輸入圖片說明


extension UIView {
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
}

這是Peter DeWeese回答的類別,允許使用 keypath layer.borderUIColor設置邊框顏色。

CALayer+XibConfiguration.h:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer(XibConfiguration)

// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;

@end

CALayer+XibConfiguration.m:

#import "CALayer+XibConfiguration.h"

@implementation CALayer(XibConfiguration)

-(void)setBorderUIColor:(UIColor*)color
{
    self.borderColor = color.CGColor;
}

-(UIColor*)borderUIColor
{
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Swift 3如果你想在使用 IBInspectable 時在 IB 中看到結果,你必須擴展 UIView 並將屬性添加到該類中,即

@IBDesignable class MyView: UIView {}

extension MyView {
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }

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

    @IBInspectable var borderColor: UIColor {
        get {
            return UIColor.init(cgColor: layer.borderColor!)
        }
        set {
            layer.borderColor = newValue.cgColor
        }
    }
}

參考: http : //nshipster.com/ibinspectable-ibdesignable/

簡短的回答:

layer.cornerRadius = 10
layer.borderWidth = 1
layer.borderColor = UIColor.blue.cgColor

長答案:

圓角 UIButton

customUIView.layer.cornerRadius = 10

邊框厚度

pcustomUIView.layer.borderWidth = 1

邊框顏色

customUIView.layer.borderColor = UIColor.blue.cgColor

您可以設置 UIButton 用戶定義的運行時屬性,即 borderWidth、cornerRadius、borderColor 等。如圖所示。 注意:-不要使用層。 在屬性名稱之前,它將不起作用。

在此處輸入圖片說明

您可以使用一段代碼,如:

self.addButton.layer.borderColor = [[UIColor greenColor] CGColor];

請注意: addButton是一個 IBOutlet。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM