我有一个每 0.1 秒重复一次的时间(我这样做是因为我需要不断地寻找我正在提取的网站文本的变化)。我的问题是我需要能够判断文本何时从一个词变为另一个词。因此,当用户打开应用程序时,假设文本显示的是一首歌曲的标题,但随后它变成了另一首,在它发生变化的地方,我需要能够检测到它并执行一个 Action 。
此外,它还必须在应用程序首次加载时不会执行操作,但当文本更改时会显示它(必须是这样,因为我正在提取歌曲标题)。所以我需要能够更改每首歌曲的持续时间,但是如果正在播放歌曲并且他们在播放中间打开应用程序,持续时间将会混淆。所以我有两个标签,一个显示文本,另一个显示时间。当应用程序首次加载时,我希望它在歌曲标题中的文本更改之前不显示任何内容,然后从 if 语句(如下)中提取持续时间。这可能有点令人困惑,但请提出您需要的任何问题,我会尽力解释。
这是我从网站上提取的代码以及其他任何可能有用的代码:
- (void)viewDidLoad {
[super viewDidLoad];
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(recentTracksText) userInfo:nil repeats:YES];
}
-(void)recentTracksText {
textForBlog = [webViewForRecents stringByEvaluatingJavaScriptFromString:@"document.getElementById('current_song').textContent;"];
self.strippedTextForBlog = [self stringByStrippingHTMLFromString:textForBlog];
continuousLabel.text = self.strippedTextForBlog;
}
if ([continuousLabel.text isEqual: @"Lady Gaga - Gypsy"]) {
imageView1.image = [UIImage imageNamed:@"Lady Gaga - Gypsy.jpg"];
imageView.hidden = YES;
[self.view insertSubview:toolbar belowSubview:imageView];
[toolbar insertSubview:darkView belowSubview:imageView];
[self.view insertSubview:backgroundImage belowSubview:toolbar];
if([darkView.subviews containsObject:continuousLabel]) {
} else{
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
[darkView addSubview:Label];
[Label setText:@"1:30"];
[darkView addSubview:continuousLabel];
});
}
}
更新
-(void)recentTracksText {
textForBlog = [webViewForRecents stringByEvaluatingJavaScriptFromString:@"document.getElementById('current_song').textContent;"];
self.strippedTextForBlog = [self stringByStrippingHTMLFromString:textForBlog];
if (![self.strippedTextForBlog isEqualToString:continuousLabel.text])// this does not find when the text changes {
[self.pLabel setHidden:NO];
[self.pLabel setProgress:1
timing:TPPropertyAnimationTimingEaseOut
duration:150.0
delay:0.0]; //This does not go smoothy.
// this does not
}
continuousLabel.text = self.strippedTextForBlog;
}
最佳答案
Use Key-value observing if you want to observe the property directly
[continuousLabel addObserver:self
forKeyPath:@"text"
options:0
context:NULL];
Make sure you implement the observing method
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
// Insert your code here to deal with the change.
}
还有一点 ARC 管理的味道:
- (void)dealloc {
NSLog(@"dealloc %@", [self class]);
if (continuousLabel) {
[continuousLabel removeObserver:self forKeyPath:@"text"];
}
}
关于ios - 检测 UILabel 文本的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483636/