1

这是我的代码:

 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 个字符的限制”...

但我目前的结果是:

在此处输入图像描述

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

4

2 回答 2

1

您需要translatesAutoresizingMaskIntoConstraints在标签falseisActive设置true约束条件。基本上你的约束代码应该是这样的:

accessoryView.leadingAnchor.constraintEqualToAnchor(label.leadingAnchor, constant: 18).isActive = true
accessoryView.centerYAnchor.constraintEqualToAnchor(label.centerYAnchor).isActive = true
于 2017-05-16T18:25:58.393 回答
0

根据我的理解,试试这个:

斯威夫特 3

let accessoryView = UIView()
let label         = UILabel()
let counterLabel  = UILabel()//This is the counter label

label.text        = "You have a 100 character limit"
counterLabel.text = "100"

accessoryView.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44)

accessoryView.backgroundColor = UIColor.red

accessoryView.addSubview(label)
accessoryView.addSubview(counterLabel)

// to setup contraint set below property to false.
label.translatesAutoresizingMaskIntoConstraints = false
counterLabel.translatesAutoresizingMaskIntoConstraints = false

//label constrint with 0 padding from left side. To change padding from left and right side, change the constant value.
accessoryView.leadingAnchor.constraint(equalTo: label.leadingAnchor, constant: 0).isActive = true

accessoryView.centerYAnchor.constraint(equalTo: label.centerYAnchor).isActive = true

//counterl=Label constrint with 0 padding from right side
        accessoryView.trailingAnchor.constraint(equalTo:counterLabel.trailingAnchor, constant: 0).isActive = true

accessoryView.centerYAnchor.constraint(equalTo: counterLabel.centerYAnchor).isActive = true

textView.inputAccessoryView = accessoryView
于 2017-05-16T19:25:25.603 回答