我想从@IBInspectabale
创建一个键盘选择如何实现这个
我正在创建一个视图,其中我插入了一个ImageView和一个TextField, 现在我将这个自定义视图类创建为@IBDesignable并创建了@IBInspectable元素。
我成功创建了侧面图像和占位符元素,但现在我正在尝试创建键盘类型但面临问题。
代码剪辑:`import UIKit
@IBDesignable class 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!
}
}
}
我通过创建枚举来尝试它,但它没有给我任何结果。
答案 0 :(得分:2)
无法为@IBInspectable
变量使用枚举类型。您必须将var设置为String
或Int
。
来自Apple的文档:
您可以将IBInspectable属性附加到类中的任何属性 声明,类扩展或任何类型的类别 Interface Builder定义的运行时属性支持: 布尔值,整数或浮点数,字符串,本地化字符串, 矩形,点,大小,颜色,范围和零。
答案 1 :(得分:0)
首先感谢大家。 我的问题解决了,没有做任何额外的努力创建枚举和所有。 我使用了苹果预定义的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 @ #)