ios - 使用自动布局创建的 UILabel 不显示 NSMutableAttributedString 的属性
<p><p>我有一个使用编程自动布局创建的 UILabel 对象 <code>calloutLabel</code>:</p>
<pre><code>- (void)setupCalloutLabel
{
UILabel *calloutLabel = ;
calloutLabel.backgroundColor = ;
calloutLabel.textAlignment = NSTextAlignmentCenter;
calloutLabel.numberOfLines = 2;
_calloutLabel = calloutLabel;
;
NSNumber *padding = @(10.0f);
NSNumber *calloutLabelHeight = @(132.0f);
NSDictionary *calloutLabelMetrics = NSDictionaryOfVariableBindings(padding, calloutLabelHeight);
UIImageView *logoImageView = _logoImageView;
NSDictionary *ecalloutLabelViews = NSDictionaryOfVariableBindings(calloutLabel, logoImageView);
NSLayoutConstraint *calloutLabelHorizontalConstraint = [NSLayoutConstraint constraintWithItem:calloutLabel
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:0.0f];
NSArray *calloutLabelVerticalConstraints = -(padding)-"
options:NSLayoutFormatAlignAllCenterX
metrics:calloutLabelMetrics
views:ecalloutLabelViews];
;
;
;
;
}
</code></pre>
<p>在后面的代码中,我用以下内容动态更新了 <code>_calloutLabel.attributedText</code>:</p>
<pre><code> NSString *calloutString = offer;
NSMutableAttributedString *calloutAttributedString = [ initWithString:calloutString];
NSString *firstLine = nil;
NSScanner *calloutScanner = ;
;
NSRange firstLineRange = NSRangeFromString(firstLine);
NSDictionary *firstLineAttributes = @{NSFontAttributeName : ,
NSForegroundColorAttributeName : };
;
NSString *secondLine = nil;
;
NSRange secondLineRange = NSRangeFromString(secondLine);
NSDictionary *secondLineAttributes = @{NSFontAttributeName :,
NSForegroundColorAttributeName : };
;
_calloutLabel.attributedText = calloutAttributedString;
</code></pre>
<p>它应该是这样的:
<img src="/image/pUR1U.png" alt="enter image description here"/> </p>
<p>实际上是这样的:
<img src="/image/XQukX.png" alt="enter image description here"/> </p>
<p>我是不是在某个地方犯了错误? </p>
<p>谢谢!</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>NSRangeFromString 用于从它的字符串表示中创建一个范围(例如@“{1,5}”),而不是获取扫描字符串的范围。</p>
<p>您真正想要做的是将范围设置为扫描仪位置,所以</p>
<pre><code>NSRange firstLineRange = NSMakeRange(0, calloutScanner.scanLocation);
</code></pre>
<p>对于第二个位置,您可以跳过扫描,只需使用字符串的长度</p>
<pre><code>NSRange secondLineRange = NSMakeRange(firstLineRange.length + 1, - firstLineRange.length - 1);
</code></pre></p>
<p style="font-size: 20px;">关于ios - 使用自动布局创建的 UILabel 不显示 NSMutableAttributedString 的属性,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/27005774/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/27005774/
</a>
</p>
页:
[1]