Swift 2.x项目迁移Swift 4:UITextView相关API适配问题求助
Hey there! I totally get how frustrating those API breakages can be when jumping from Swift 2 to 4—let's fix these two issues step by step.
1. Fixing the CGRect.insetBy Error
Your current code CGRect.insetBy(view.bounds, 10, 10) is throwing an error because insetBy(dx:dy:) is an instance method, not a class method in Swift 3+.
In Swift 2, you used the global CGRectInset() function, but Swift 3+ moved this to be a method you call directly on a CGRect instance (like view.bounds). You also need to include the parameter labels dx and dy—Swift enforces these for clarity now.
Correct Code:
// Call insetBy() directly on your CGRect instance (view.bounds) let textViewFrame = view.bounds.insetBy(dx: 10, dy: 10) let textView = UITextView(frame: textViewFrame)
2. Replacing UIEdgeInsetsZero
In Swift 3+, UIEdgeInsetsZero was deprecated in favor of the static property UIEdgeInsets.zero. This is a cleaner, more consistent way to get empty edge insets.
Example Usage:
If you were setting something like textView.contentInset = UIEdgeInsetsZero before, replace it with:
textView.contentInset = UIEdgeInsets.zero
If you ever need custom edge insets, you can also use the initializer directly:
// For non-zero insets let customInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) textView.contentInset = customInsets
Quick Pro Tip
Xcode has a built-in tool to handle most of these syntax changes automatically! Go to Edit > Convert > To Current Swift Syntax... and follow the prompts—it'll fix a lot of these API replacements for you, saving you manual work.
内容的提问来源于stack exchange,提问作者user2296278

