swift - 标签显示在屏幕顶部而不是在 inputAccessoryView 上

标签 swift autolayout textview inputaccessoryview

这是我的代码:

 var messageView : UITextView = {
        var textView = UITextView()
        textView.text = "   Add your message here"
        textView.textColor = UIColor.lightGrayColor()
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.backgroundColor = UIColor.lightGrayColor()
        textView.layer.cornerRadius = 3
        textView.clipsToBounds = true
        textView.keyboardAppearance = .Dark
        textView.layer.borderWidth = 1.0
        textView.layer.borderColor = UIColor.lightGrayColor()
        textView.autocorrectionType = .no


        // MARK: Setup accesorryView

        let label = UILabel()
        label.text = "You have a 100 character limit"
        label.translatesAutoresizingMaskIntoConstraints = false

        let accessoryView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44))
        accessoryView.backgroundColor = UIColor.redColor()

        accessoryView.addSubview(label)

        accessoryView.leadingAnchor.constraintEqualToAnchor(label.leadingAnchor, constant: 18)
        accessoryView.centerYAnchor.constraintEqualToAnchor(label.centerYAnchor)

        textView.inputAccessoryView = accessoryView

        return textView
    }()

我正在尝试将 inputAccessoryView 添加到我的 TextView 的键盘。 我的 inputAccessoryView 必须有一个标签,上面写着“你有 100 个字符的限制”...

但我目前的结果是:

enter image description here

蓝色的文本...正是我想要在 inputAccessoryView 中显示的标签,但它在我的屏幕顶部...

最佳答案

您需要将标签上的 translatesAutoresizingMaskIntoConstraints 设置为 false 并将约束上的 isActive 设置为 true。基本上你的约束代码应该是这样的:

accessoryView.leadingAnchor.constraintEqualToAnchor(label.leadingAnchor, constant: 18).isActive = true
accessoryView.centerYAnchor.constraintEqualToAnchor(label.centerYAnchor).isActive = true

关于swift - 标签显示在屏幕顶部而不是在 inputAccessoryView 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44008908/

相关文章:

ios - UITableViewAutomaticDimension 的约束错误

ios - dequeueReusableCell 导致文本改变颜色

android - 在自定义 View 中组合 android 组件

swift - 在 Swift 的 NSTextfield 中设置最大字符数(为一个)

ios - TextView 点按在 iOS 14 上不起作用

ios - 如何强制ios执行自动布局?

android - 水平滚动 TextView 将长文本分页(如 Kindle)?

ios - 用户信息中带有自定义对象的 UNMutableNotificationContent 使应用程序崩溃

ios - Fetch Request 执行方法不返回任何内容

ios - 如何使用 Masonry mas_makeConstraints 避免冲突?