这是我的代码
class AmDocViewController: UIViewController,UITextViewDelegate {
var text1:String!
let replaceYName: String = "text1"
var textA:String!
let replaceFName: String = "textA"
var textB:String!
let replaceyGFName: String = "textB"
@IBOutlet weak var myTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
myTextView.delegate = self;
self.view.endEditing(true)
let notes37 = NSAttributedString(string:"""
(SOME SAMPLE TEXT......)
""", attributes:[NSAttributedStringKey.foregroundColor: UIColor.gray])
let newMutableString77 = notes37.mutableCopy() as! NSMutableAttributedString
newMutableString77.append(notes37)
myTextView.attributedText = newMutableString77 as NSAttributedString
let originalString = myTextView.text
let updatedString = originalString?.replacingOccurrences(of: replaceYName, with: text1)
let updatedString1 = updatedString?.replacingOccurrences(of: replaceFName, with: textA)
if textB == "" {
let updatedString2 = updatedString1?.replacingOccurrences(of: str25, with: "N/A")
}
if textB != ""{
let updatedString2 = updatedString1?.replacingOccurrences(of: replaceyGFName, with: textB)
}
myTextView.text = updatedString2
myTextView.textAlignment = NSTextAlignment.center
}
在if语句行中获取以下错误消息
Argument type 'NSAttributedString' does not conform to expected type 'StringProtocol'
请建议如何使用从其他ViewController TextField(text1)接收的String值并替换TextView中的属性String?
答案 0 :(得分:0)
<强>首先:强> Apple文档定义的StringProtocol:
可以将字符串表示为字符集合的类型。
我假设变量str25
是NSAttributedString
这是导致错误的原因。确保您传递到replacingOccurrences(of:with:)
的变量属于String
您可以采取的另一种方法是将String
转换为NSMutableAttributedString
,此对象具有var mutableString: NSMutableString { get }
属性
返回可变字符串对象
然后您可以在replacingOccurrences(of:with:)
方法