程序內(nèi)實(shí)現(xiàn)console控制臺(tái)打印

{
UIButton *logBtn = [UIButton buttonWithType:UIButtonTypeCustom];
logBtn.frame = CGRectMake(0, kStatusBarHeight, 100, 30);
[logBtn setTitle:@"console" forState:UIControlStateNormal];
logBtn.backgroundColor = UIColor.grayColor;
[logBtn setTitleColor:UIColor.greenColor forState:UIControlStateNormal];
[logBtn addTarget:self action:@selector(logBtnAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logBtn];

textView = [[UITextView alloc]initWithFrame:CGRectMake(0,kStatusBarHeight+30, kScreenWidth, kScreenWidth)];
textView.backgroundColor = [UIColor.yellowColor colorWithAlphaComponent:0.25];
[self.view addSubview:textView];
textView.hidden = YES;
[self redirectSTD:STDOUT_FILENO];
[self redirectSTD:STDERR_FILENO];

}
-(void)logBtnAction{
textView.hidden = !textView.hidden;
}

  • (void)redirectNotificationHandle:(NSNotification *)nf{ // 通知方法
    NSData *data = [[nf userInfo] objectForKey:NSFileHandleNotificationDataItem];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    textView.text = [NSString stringWithFormat:@"%@\n\n%@",textView.text, str];// logTextView 就是要將日志輸出的視圖(UITextView)
    NSRange range;
    range.location = [textView.text length] - 1;
    range.length = 0;
    [textView scrollRangeToVisible:range];
    [[nf object] readInBackgroundAndNotify];
    }

  • (void)redirectSTD:(int )fd{
    NSPipe * pipe = [NSPipe pipe] ;// 初始化一個(gè)NSPipe 對(duì)象
    NSFileHandle *pipeReadHandle = [pipe fileHandleForReading] ;
    dup2([[pipe fileHandleForWriting] fileDescriptor], fd) ;

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(redirectNotificationHandle:)
    name:NSFileHandleReadCompletionNotification
    object:pipeReadHandle]; // 注冊(cè)通知
    [pipeReadHandle readInBackgroundAndNotify];
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容