gpt4 book ai didi

ios - 设置后 UITextView 属性文本为空

转载 作者:可可西里 更新时间:2023-11-01 03:06:54 25 4
gpt4 key购买 nike

我有一个带有不可编辑、不可选择的 UITextView 的自定义 UICollectionViewCell。在 cellForItemAtIndexPath: 方法中,我设置了 UITextView 的 attributedText 属性,它可以很好地显示所有属性。但是,当我稍后尝试访问该属性文本时(在点击手势识别器的操作方法中),该值为空。

这是我的代码:

View Controller :

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
TNCommentCollectionViewCell *commentCell = [collectionView dequeueReusableCellWithReuseIdentifier:kCommentCellIdentifier
forIndexPath:indexPath];

TNComment *comment = [self.comments objectAtIndex:indexPath.row];
commentCell.textView.attributedText = [self commentStringForComment:comment];

return commentCell;
}

- (NSAttributedString *)commentStringForComment:(DAFeedComment *)comment
{
NSString *usernameString = [NSString stringWithFormat:@"@%@", comment.username];
NSDictionary *usernameAttributes = @{ NSForegroundColorAttributeName : [UIColor usernameColor],
NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0f] };
NSAttributedString *attributedUsernameString = [[NSAttributedString alloc] initWithString:usernameString attributes:usernameAttributes];
NSMutableAttributedString *labelString = [attributedUsernameString mutableCopy];

NSDictionary *commentAttributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0f] };
[labelString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
[labelString appendAttributedString:[[NSAttributedString alloc] initWithString:comment.comment attributes:commentAttributes]];

return labelString;
}

Collection View 单元格:

- (void)awakeFromNib
{
[super awakeFromNib];

self.textView.textContainerInset = UIEdgeInsetsZero;

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped:)];
tapGesture.numberOfTapsRequired = 1;
[self.textView addGestureRecognizer:tapGesture];
}

- (void)textViewTapped:(UITapGestureRecognizer *)recognizer
{
UITextView *textView = (UITextView *)recognizer.view;

NSLayoutManager *layoutManager = textView.layoutManager;
CGPoint location = [recognizer locationInView:textView];
location.x -= textView.textContainerInset.left;
location.y -= textView.textContainerInset.top;

NSUInteger characterIndex = [layoutManager characterIndexForPoint:location
inTextContainer:textView.textContainer
fractionOfDistanceBetweenInsertionPoints:nil];

if( characterIndex < textView.textStorage.length )
{
NSLog(@"%@", textView.attributedText);
}
}

这导致输出只是“(null)”。但是,如果我打印 UITextView 的文本属性,它将打印实际文本,而不是属性文本。

我做错了什么吗?非常感谢任何帮助

谢谢!

最佳答案

我遇到了同样的问题。我的解决方案是在 Storyboard中启用 UITextView 可选属性。之后一切正常。

希望对你有帮助

关于ios - 设置后 UITextView 属性文本为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com