小编ric*_*h24的帖子

使用Swift中的NSMutableAttributedString更改特定文本的颜色

我遇到的问题是我希望能够在TextView中更改某些文本的textColor.我使用的是串联字符串,只是希望我附加到TextView文本中的字符串.似乎我想要使用的是NSMutableAttributedString,但我没有找到任何有关如何在Swift中使用它的资源.到目前为止我所拥有的是这样的:

let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)

从这里我知道我需要找到需要更改textColor的单词范围,然后将它们添加到属性字符串中.我需要知道的是如何从attributionString中找到正确的字符串,然后更改它们的textColor.

由于我的评分太低,我无法回答我自己的问题,但这是我找到的答案

我通过翻译来翻译一些代码来找到我自己的答案

更改NSAttributedString中子字符串的属性

以下是Swift中的实现示例:

let string = "A \(stringOne) and \(stringTwo)"
var attributedString = NSMutableAttributedString(string:string)

let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
for stringOneMatch in stringOneMatches {
    let wordRange = stringOneMatch.rangeAtIndex(0)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
}

textView.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)

由于我想要更改多个字符串的textColor,我将创建一个帮助函数来处理它,但这适用于更改textColor.

ios nsmutableattributedstring swift

90
推荐指数
8
解决办法
11万
查看次数

在后台应用程序时禁用AVPictureInPictureController的镜像

由于我们的内容提供商的要求,我们的应用程序需要能够禁用Airplay镜像我们的播放器的功能,同时在应用程序在背景中的画中画.

当应用程序在前台时,我们会观察UIScreenDidConnectNotification,并利用它来呈现另一个屏幕,但是当应用程序进入后台时,观察者不会得到通知,直到应用程序返回到前台.这允许我们的DRM视频内容镜像到AppleTV,而画中画是活动的.

我们还尝试观察AVPlayer实例的'isExternalPlaybackActive'属性,但即使使用AVPlayerViewController的示例项目,我们也无法观察到该值的任何更改.通过计时器,我们还验证了即使应用程序位于前台,而AVPlayer实例也是全屏的,当镜像内容时,值不会发生变化.Key Value Observing唯一一次显示值更改是在最初设置时.

我们还尝试设置一个计时器,使用NSOperation将在后台继续,而画中画是活动的.在画中画处于活动状态且后台应用程序中,观察到UIScreen.screens.count没有更改,保持相同的值1.还观察到AVPlayer实例的isExternalPlaybackActive属性仍为"false" .

我们做的另一个尝试是设置AVPlayer的'usesExternalPlaybackWhileExternalScreenIsActive'和'allowsExternalPlayback',但这也阻止了播放器通过Airplay Mirroring显示.

通过这些尝试,我们已经耗尽了文档中的资源,并希望找到一种解决方案,仍然允许我们在后台使用应用启用画中画.

ios

11
推荐指数
0
解决办法
234
查看次数

标签 统计

ios ×2

nsmutableattributedstring ×1

swift ×1