2016-09-20 73 views
2

的問題
我已經子類一個UITextView並添加了UILabel作爲一個子視圖。我想將標籤放在右下角。曖昧約束添加的UILabel當作爲子視圖的UITextView

代碼

fileprivate lazy var counterLabel: UILabel = { 
    let label = UILabel() 
    label.translatesAutoresizingMaskIntoConstraints = false 

    self.addSubview(label) 

    // add constraints 
    self.addConstraints([ 
     NSLayoutConstraint(item: label, equalTo: self, attribute: .right), 
     NSLayoutConstraint(item: label, equalTo: self, attribute: .bottom)] 
    ) 

    return label 
    }() 

截圖
enter image description here

如在上面的截圖所示,紅色標籤被示出爲具有一個ambiguous layout

如果我使用一個情節串連圖板,並添加相同的兩個約束(底部,右側)標籤沒有模棱兩可的立場。我做錯了什麼?

+0

標籤如何成爲文本視圖的子視圖?文本視圖是可滾動的;它會將標籤滾動到視線之外。 – matt

+0

啊我一直很蠢!謝謝你的幫助! – Ollie

回答

1

你想要的是一個超級視角。將標籤和textview作爲子視圖添加到此超級視圖。

1

問題可能是由於嚴格的限制。所有的標籤都有自己的約束條件,因爲裏面的文本而擴展。這種限制有一些優先事項。可能的問題可能是您創建的約束具有較低的優先級,這會導致此類問題。嘗試使用全功能創建約束。這對我來說可以。這是我的代碼與文本字段。

self.leadingLabelConstraint = [NSLayoutConstraint constraintWithItem:_markLabel 
                   attribute:NSLayoutAttributeLeading 
                   relatedBy:NSLayoutRelationEqual 
                    toItem:self 
                   attribute:NSLayoutAttributeLeading 
                   multiplier:1.0 constant:0]; 
    self.topLabelConstraint = [NSLayoutConstraint constraintWithItem:_markLabel 
                  attribute:NSLayoutAttributeTop 
                  relatedBy:NSLayoutRelationEqual 
                   toItem:self 
                  attribute:NSLayoutAttributeTop 
                  multiplier:1.0 constant:0]; 
    [self.superview addConstraints:@[self.topLabelConstraint, self.leadingLabelConstraint]]; 
    self.heightLabelConstraint = [NSLayoutConstraint constraintWithItem:_markLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:20]; 
    [self.markLabel addConstraint:self.heightLabelConstraint]; 

自我是 - 的UITextField

和markLabel是 - 的UILabel。