【问题标题】:iOS adding variable to label's textiOS将变量添加到标签的文本
【发布时间】:2014-05-11 16:46:21
【问题描述】:

我一直在开发一款 iOS 应用,但在其中一个屏幕上遇到了一些复杂问题。

这个名为“about”的屏幕只有两个标签:它们应该显示当前的用户名和时间。

标签的文本加载良好,但我无法让它们显示带有用户名和当前时间的变量。

这是我的代码:

关于.h

@interface About : UIViewController

@property (weak) IBOutlet UILabel * username;
@property (weak) IBOutlet UILabel * date;

@property (strong, nonatomic) NSString * usuari;
@property (strong, nonatomic) NSString * data;
@property (strong, nonatomic) NSString * name;
@property (strong, nonatomic) NSString * currentTime;

关于.m

#import "About.h"

@interface About()
@end

@implementation About

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILabel * username = [[UILabel alloc] initWithFrame:CGRectMake(162, 106, 150, 72)];
    [self.view addSubview: username];
    username.text = @"Usuari: ";
    username.numberOfLines = 4;
    username.textColor = [UIColor blackColor];
    username.text = [NSString stringWithFormat:@"Usuari: ", _usuari];

    UILabel * date = [[UILabel alloc] initWithFrame:CGRectMake(160, 261, 1488, 44)];
    [self.view addSubview: date];
    date.text = @"Hora: ";
    date.numberOfLines = 4;
    date.textColor = [UIColor blackColor];
    date.text = [NSString stringWithFormat:@"Hora: ", _currentTime];

}

-(void) gettingUser
{
    [[UIDevice currentDevice] name];
    self.username.text = self.name;
}

-(void) gettingTime
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];

    self.date.text = self.currentTime;
    //self.date.text = [NSDate date];

    //NSTimer schedule interval
    //NSDateFormatter alloc
}


@end

你能帮我弄清楚我需要做什么才能让它工作吗?

【问题讨论】:

    标签: ios variables nsstring uilabel


    【解决方案1】:

    变量未显示的原因是没有格式说明符。我也很惊讶您没有收到上述代码的编译器警告或错误。

    这行代码:

     username.text = [NSString stringWithFormat:@"Usuari: ", _usuari];
    

    应该这样写 - 不是这样吗?

        username.text = [NSString stringWithFormat:@"Usuari:%@ ", _usuari];
    

    _usuari 是变量,%@ 是格式说明符,您希望在其中放置该变量。

    在这之后:ursername.text 应该像这样打印出来:Usuari: variable value

    【讨论】:

    • @user3082271 由于格式字符串和参数不匹配,Xcode 肯定会显示原始代码存在问题。不要忽略此类信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2014-12-19
    • 1970-01-01
    • 2016-10-17
    • 2021-07-11
    • 2019-07-16
    • 2019-11-08
    相关资源
    最近更新 更多