简体   繁体   English

如何在NSTextField中获取值?

[英]How can I get the value inside of an NSTextField?

My NSTextField contains doubles like "1.67" or "0.05" etc. 我的NSTextField包含诸如“ 1.67”或“ 0.05”等的双打。

When I try the following: 当我尝试以下操作时:

console.log([priceChange doubleValue]); //priceChange is an NSTextField

    //Apply styles
    if([priceChange doubleValue] > 0)
        [priceChange setTextColor:[NSColor greenColor]];
    else if([priceChange doubleValue] < 0)
        [priceChange setTextColor:[NSColor redColor]];
    else if([priceChange doubleValue] == 0)
        [priceChange setTextColor:[NSColor blackColor]];

priceChange is equal to 0 always, even when the value is something else. priceChange始终等于0,即使该值是其他值也是如此。 How can I properly get the value of priceChange? 如何正确获得priceChange的值?

Try [[priceChange stringValue] floatValue] . 尝试[[priceChange stringValue] floatValue] Also make sure there is nothing other than whitespace before the number in the string, or floatValue will return 0. 另外,请确保字符串中的数字之前没有空格,否则,floatValue将返回0。

This is precisely what NSNumberFormatter is for. 这正是NSNumberFormatter的用途。 Give your field a suitable formatter (easy to add/setup in IB), and -objectValue will start returning an NSNumber . 给您的字段一个合适的格式化程序(易于在IB中添加/设置),并且-objectValue将开始返回NSNumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM