5

我想从@IBInspectabale 创建一个键盘选择

键盘选择

如何实现这一目标

我正在创建一个视图,在其中插入一个 ImageView 和一个 TextField,现在我正在将此自定义视图类创建为 @IBDesignable 并创建 @IBInspectable 元素。

我成功地创建了侧面图像和占位符元素,但现在我正在尝试创建键盘类型但面临问题。

代码剪断:`导入UIKit

@IBDesignable 类 CustomTextField: UIView,UITextFieldDelegate {

//custom view from the XIB file
var view: UIView!

@IBOutlet weak var textField: UITextField!
@IBOutlet weak var imageView: UIImageView!

override init(frame: CGRect) {
    super.init(frame: frame)
    loadViewFromNib ()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    loadViewFromNib ()
}

func loadViewFromNib() {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "CustomTextField", bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
    view.frame = bounds
    view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.addSubview(view);



}

@IBInspectable var sideImage: UIImage? {
    get {
        return imageView.image
    }
    set(sideImage) {
        imageView.image = sideImage
    }
}

@IBInspectable var placeHolderText: String? {
    get {
        return textField.placeholder
    }
    set(placeHolderText) {
        textField.placeholder = placeHolderText
    }
}'

以上所有工作正常,但以下对我不起作用:

@IBInspectable var keyboard: UIKeyboardType? {
    get{
        return UIKeyboardType(rawValue: textField.keyboardType.rawValue)
    }
    set(keyboard){
        textField.keyboardType = keyboard!
    }
}

}

我通过创建枚举来尝试它,但它没有给我任何结果。

4

2 回答 2

7

首先感谢大家。我的问题得到了解决,而无需付出任何额外的努力来创建枚举和所有内容。我使用了苹果预定义的 UIKeyboardType 枚举。只需编写以下代码:

@IBInspectable var keyboard:Int{
    get{
        return self.textField.keyboardType.rawValue
    }
    set(keyboardIndex){
        self.textField.keyboardType = UIKeyboardType.init(rawValue: keyboardIndex)!

    }
}

它会在界面生成器中显示键盘,您可以为您的键盘类型设置 0,1,2... 值。其中 0,1,2 表示如下:

0: default // Default type for the current input method.

1: asciiCapable // Displays a keyboard which can enter ASCII characters

2: numbersAndPunctuation // Numbers and assorted punctuation.

3: URL // A type optimized for URL entry (shows . / .com prominently).

4: numberPad // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.

5: phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).

6: namePhonePad // A type optimized for entering a person's name or phone number.

7: emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

8: decimalPad // A number pad with a decimal point.

9: twitter // A type optimized for twitter text entry (easy access to @ #)
于 2017-05-03T12:59:31.237 回答
3

不能对@IBInspectablevar 使用枚举类型。您必须将您的 var 设置为 aStringInt

来自 Apple 的文档:

对于 Interface Builder 定义的运行时属性支持的任何类型,您可以将 IBInspectable 属性附加到类声明、类扩展或类别中的任何属性:布尔值、整数或浮点数、字符串、本地化字符串、矩形、点、大小、颜色、范围和零。

于 2017-05-03T10:54:50.527 回答