实现效果
源代码
注:@开头的这些代码都是需要关联控键,都需要自行在故事板中(Storyboards)进行关联
import UIKit
class ViewController: UIViewController,UITextFieldDelegate,UITextViewDelegate {
//定义label等各个控件
let label1 = UILabel(frame:CGRect(x:80,y:30,width:220,height:40))
let label2 = UILabel(frame:CGRect(x:30,y:80,width:100,height:40))
let input = UITextView(frame:CGRect(x:30,y:120,width:360,height:200))
let label3 = UILabel(frame:CGRect(x:30,y:330,width:150,height:40))
let key = UITextField(frame:CGRect(x:160,y:330,width:200,height:40))
let label4 = UILabel(frame:CGRect(x:50,y:370,width:300,height:60))
var keyword: String = " "
var paragraph: String = " "
override func viewDidLoad() {
super.viewDidLoad()
label1.text = "检索段落中关键字出现次数"
label1.textColor = UIColor.blue
label2.text = "请输入段落:"
label2.textColor = UIColor.blue
input.backgroundColor = UIColor.green
input.textColor = UIColor.blue
label3.text = "请输入关键字:"
label3.textColor = UIColor.blue
key.borderStyle = UITextBorderStyle.line
key.placeholder = "请输入关键字"
label4.text = "关键字出现次数:?????"
label4.textColor = UIColor.blue
input.delegate = self
key.delegate = self
self.view.addSubview(label1)
self.view.addSubview(label2)
self.view.addSubview(input)
self.view.addSubview(label3)
self.view.addSubview(label4)
self.view.addSubview(key)
}
//定义单词检索函数
func searchKeyword(theString:String,theSubs:String)->Int{
let countsOfKeyword = theString.components(separatedBy: theSubs).count-1
return countsOfKeyword
}
func textView(_ textView:UITextView,shouldChangeTextIn range:NSRange,replacementText text:String)->Bool{
if(text == "\n")
{
self.key.becomeFirstResponder()
}
return true
}
//定义结果函数
func textField(_ textField:UITextField,shouldChangeCharactersIn range:NSRange,replacementString string:String)->Bool{
keyword = key.text!
paragraph = input.text
let counts = searchKeyword(theString:paragraph,theSubs:keyword)
label4.text = " 关键字: \(keyword)出现了\(counts)次"
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}