2017-09-01 44 views
0

我正在做一個聊天界面。我創建了一個用於顯示文本消息的文本視圖。 當我使用sizeToFit爲textview。它始終sizeToFit從X(左)邊緣。我需要從視圖的右側設置小信息。框架從右邊對齊sizeToFit

enter image description here

這裏是我的TextView的代碼。

UITextView *TextLbl = [[UITextView alloc]initWithFrame:CGRectMake(self.navigationController.navigationBar.frame.size.width-220, cell.frame.origin.y, 210, 60)]; 
TextLbl.textAlignment=NSTextAlignmentRight; 
    TextLbl.contentMode=UIViewContentModeRight; 
TextLbl.editable=NO; 
    [TextLbl sizeToFit]; 
    [TextLbl.textContainer setSize:TextLbl.frame.size]; 

回答

0

-sizeToFit設置的UITextView的CGSize,但不做任何修改,其中在上海華的元件放置。根據您選擇的佈局系統(自動佈局等),您可以通過不同的方式實現對齊右側邊緣的textview。

+0

我該怎麼設置框的右對齊。? –

0

要實現這一點,要麼使用佈局約束或計算文本的大小設置爲textview和x的相同大小將screenWidth-textview.width。

編輯

添加約束如下圖所示代碼:

UITextView *TextLbl = [[UITextView alloc]init]; 
[self.view addSubview:TextLbl]; 
[TextLbl setTranslatesAutoresizingMaskIntoConstraints:NO]; 
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:TextLbl attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:TextLbl.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10]]; 
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:TextLbl attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:TextLbl.superview attribute:NSLayoutAttributeWidth multiplier:1.0 constant:-10]]; 
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:TextLbl attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:TextLbl.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:100]]; 

[TextLbl setText:@"Hello there!"]; 
[TextLbl setBackgroundColor:[UIColor redColor]]; 
TextLbl.textAlignment=NSTextAlignmentRight; 
TextLbl.contentMode=UIViewContentModeRight; 
TextLbl.editable=NO; 
TextLbl.scrollEnabled = NO; 

你可能調整的約束,按您的佈局。

+0

你能請請引用我任何有用的鏈接..我卡在那一點 –

+0

@VarinderSingh請檢查更新的答案。 –

+0

原因:'無法爲視圖層次設置佈局而未準備好約束 –

0

Solution--

- (void)sizeToFitWithAlignmentRight :(UILabel *)label { 
CGRect beforeFrame = label.frame; 
[label sizeToFit]; 
CGRect afterFrame = label.frame; 
label.frame = CGRectMake(beforeFrame.origin.x + beforeFrame.size.width - afterFrame.size.width, label.frame.origin.y, label.frame.size.width, label.frame.size.height); 
}