在 Swift 中指定 UITextField 的边框半径

Specify border radius of UITextField in Swift

我想使用 Swift.

以编程方式指定 UITextField 的边界半径

默认情况下,UITextField 的边界半径很小,但我想增加它,在通过 Interface Builder 搜索之后,我认为这可以通过编程方式完成吗?

您可以使用:

nameOfTextField.layer.cornerRadius = 15.0
nameOfTextField.layer.borderWidth = 2.0
nameOfTextField.layer.borderColor = UIColor.red.cgColor

试试这个:yourTxtField.layer.cornerRadius 您还可以在这里找到其他方法 https://developer.apple.com/library/prerelease/tvos/documentation/UIKit/Reference/UITextField_Class/index.html

正如@SnarfSnarf 建议的那样,您可以通过访问其 layer 属性以编程方式调整文本字段的边框宽度和圆角半径,_以及任何其他相关视图:

nameOfTextField.layer.cornerRadius = 4.0
nameOfTextField.layer.borderWidth = 2.0

最重要的是,UITextField 有一个 borderStyle 属性,您可能想玩一下。它有四个可能的值:NoneLineBezelRoundedRect

终于通读了 UITextField's documentation,这总是找出 class 提供的所有可能性的好方法。

如果您使用的是 Interface Builder,则可以对要修改的控件使用用户定义的运行时属性。在运行时,当视图加载时,您为其传递键路径的每个属性都将自动设置为您的值。无需通过少量显示调整来弄乱您的代码。

下图应该可以回答您的问题。

要创建文本字段的角半径,下面的答案是正确的:

swift 3

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

创建文本字段的 borderWidth 下面的答案是正确的:

swift 3

YourTextfieldName!.layer.borderWidth = 1
YourTextfieldName!.layer.borderColor = UIColor.black.cgColor

不要忘记添加 layer.masksToBound - 我认为最受欢迎的答案错过了这一点。您需要按钮具有与其边框相同的形式。 https://developer.apple.com/documentation/quartzcore/calayer/1410896-maskstobounds

nameOfTextField.layer.cornerRadius = 15.0
nameOfTextField.layer.borderWidth = 0
nameOfTextField.layer.masksToBounds = true

这对我有用,

  nameOfTextField.layer.cornerRadius = 15.0
  nameOfTextField.layer.borderWidth = 2.0
  nameOfTextField.layer.borderColor = UIColor.brown.cgColor  
  nameOfTextField.layer.masksToBounds = true

在 Swift 5

yourTxtField.layer.cornerRadius = 18
yourTxtField.layer.masksToBounds = true

你也可以用故事板来做。只需将此扩展名写入您的扩展文件即可。然后 select 故事板中的文本字段 您将看到更改角半径的选项

extension UIView {

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

}