【ios开发/Xcode】实现关键字检索

【ios开发/Xcode】实现关键字检索

实现效果

在这里插入图片描述

源代码

注:@开头的这些代码都是需要关联控键,都需要自行在故事板中(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.
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值