首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >意外不能分配属性'self‘是类中不可变的编译时错误

意外不能分配属性'self‘是类中不可变的编译时错误
EN

Stack Overflow用户
提问于 2021-02-06 22:43:09
回答 1查看 386关注 0票数 2

这是Swift编译器的奇怪行为。我在一个类中得到一个Cannot assign to property 'self' is immutable编译时错误。下面是最低限度的操场代码:

代码语言:javascript
复制
import UIKit

open class TextInputTraitsWrapper: NSObject {
    private var wrapped: UITextInputTraits
    
    public init(wrapped: UITextDocumentProxy) {
        self.wrapped = wrapped
        super.init()
    }
    
    open var keyboardAppearance: UIKeyboardAppearance {
        get {
            return wrapped.keyboardAppearance ?? UIKeyboardAppearance.default
        }
        set {
            wrapped.keyboardAppearance = newValue // ERROR ON THIS LINE
        }
    }
}

这是我得到的错误(这是完整的程序):

另外,协议UITextInputTraits定义了keyboardAppearance,如下所示:optional var keyboardType: UIKeyboardType { get set }

为什么我在课堂上会犯这样的错误??

EN

回答 1

Stack Overflow用户

发布于 2021-02-06 23:45:45

此错误与您创建的类无关。它与变量“包装”的底层协议相关。不能直接修改keyboardAppearance属性。

相反,您需要在源代码中修改它。这是用户键入的textfield/搜索栏。

要做到这一点,只需访问UITextField /UISearchBar,并在那里更改keyboardAppearance属性即可。

代码语言:javascript
复制
textField.keyboardAppearance = UIKeyboardAppearance.dark
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66082736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档