![](/img/trans.png)
[英]In a custom UITableViewCell Hide/Unhide UILabel on Button Click
[英]Hide and Unhide button programmatically
我試圖在文本字段為空時隱藏一個按鈕,然后在用戶開始輸入時顯示它。
我嘗試為按鈕制作一個插座,在 viewDidLoad 中使用了一個 while 循環來實現按鈕和文本字段的插座。 它沒有用,我一直在四處搜索,但大部分代碼都是objective-C,所以我很難將它翻譯成swift。
甚至可以在文本字段為空時隱藏按鈕嗎?
Swift 首選
使用 UITextFieldDelegate 隱藏和顯示按鈕。
class ViewController: UIViewController,UITextFieldDelegate //set delegate to class
@IBOutlet var txtValue: UITextField //create a textfile variable
override func viewDidLoad() {
super.viewDidLoad()
txtValue.delegate = self
YourButton.hidden=false;
//set delegate to textfile
}
func textFieldDidBeginEditing(textField: UITextField!)
{ //delegate method
YourButton.hidden=true;
}
func textFieldShouldEndEditing(textField: UITextField!) -> Bool { //delegate method
return false
}
func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
也許它會幫助你。
試試這個代碼:
func textField(textField: UITextField, shouldChangeCharactersInRange range:NSRange, replacementString string: String) -> Bool
{
text = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var strMsg: String = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if strMsg.length() > 0 || text.length() > 0
{
self.YourButton.alpha = 1.0
self.YourButton.enabled = true
}
else
{
self.YourButton.alpha = 0.5
self.YourButton.enabled = false
}
return true
}
首先,您必須使用此代碼隱藏按鈕。
btn1.hidden = YES;
將 UITextFieldDelegate 分配給文件所有者后,也在 .h 文件中實現相同的委托
之后,當您開始在文本字段上寫一些文本時,您將使用此代碼。
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self updateTextLabelsWithText: newString];
return YES;
}
-(void)updateTextLabelsWithText:(NSString *)string
{
[myLabel setText:string];
}
當文本框文本運行時使用
btn1.hidden = NO;
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.