[英]How to add UI Objects (Image) to a UITextView or UITextField?
[英]How to add a method to UITextField & UITextView?
我想把這樣的東西放在UITextField
& UITextView
的方法中。
- (void)changeKeyboardType:(UIKeyboardType)keyboardType {
paymentTextView.keyboardType = UIKeyboardTypeAlphabet;
[paymentTextView resignFirstResponder];
[paymentTextView becomeFirstResponder];
}
我該怎么做呢? 我知道我可以為UITextField
和UITextView
創建類別,但是可以一次性完成嗎?
一口氣,我的意思是用一個協議將它添加到兩個類中,而不是創建兩個類別,一個用於UITextView
,一個用於UITextField
。 我聽說一個協議類似於 Ruby 模塊,但是在 Ruby 模塊中,我可以實現該方法。 在一個協議中,似乎我只能聲明方法但不能實現它。 我是否也可以實現協議中的方法,然后將此協議包含在UITextField
& UITextView
中?
如何向 Cocoa 中的現有協議添加方法? 接近但不完全。
像這樣的事情呢?
// UIView+UITextInputTraits.h
@interface UIView (UITextInputTraits)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType;
@end
// UIView+Additions.m
#import "UIView+UITextInputTraits.h"
@implementation UIView (UITextInputTraits)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType {
if ([self conformsToProtocol:@protocol(UITextInputTraits)]) {
id<UITextInputTraits> textInput = (id<UITextInputTraits>)self;
if (textInput.keyboardType != keyboardType) {
[self resignFirstResponder];
textInput.keyboardType = keyboardType;
[self becomeFirstResponder];
}
}
}
@end
對於其中的每一個,您都可以創建一個類別。
接口文件:
@interface UITextField (ChangeKeyboard)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType;
@end
實現文件:
@implementation UITextField (ChangeKeyboard)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType {
self.keyboardType = keyboardType;
[self resignFirstResponder];
[self becomeFirstResponder];
}
@end
這將是添加這些的方法,但我還沒有測試過功能。
就像@Josh 說的那樣,方法調配不是您想要的。 但是我真正想到的(我在提交答案之前沒有對其進行更多研究是不好的)是在運行時在 UITextView 和 UITextField 上添加方法。 雖然這需要更多代碼來實現,但它可以為您提供您正在尋找的那種一次性(您創建一個方法並在運行時將其添加到 UITextView 和 UITextField)
這是一篇關於它的博客文章:
http://theocacao.com/document.page/327
http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.