2017-09-01 84 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); 
}