Xcode 中 Objective-C 中的 IF 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11386222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IF statement in Objective-C in Xcode
提问by Matthew
In Xcode, I'm trying to make a button that changes it's text, relative to what the text currently is. For example: If the button says "1" and it is pressed, I want the text to change to "2" and "2" to "3" and so forth, here's the snippet of code that's giving me trouble:
在 Xcode 中,我试图制作一个按钮来更改它的文本,相对于当前文本的内容。例如:如果按钮显示“1”并按下它,我希望文本更改为“2”和“2”更改为“3”等等,这是给我带来麻烦的代码片段:
if (magicButton.titleLabel = @"1") {
[magicButton setTitle:@"2" forState:UIControlStateNormal];
}
Xcode gives me this error "Assignment to readonly property" on line one of the snippet. I'm pretty new to Objective-C and iPhone App development, so maybe it's something crazily obvious and simple. Please don't mind if that's the case.
Xcode 在代码片段的第一行给了我这个错误“分配给只读属性”。我对 Objective-C 和 iPhone 应用程序开发还很陌生,所以也许这是非常明显和简单的事情。如果是这种情况,请不要介意。
Here's a paste of my implementation fileif it would help at all.
Thanks in advance.
提前致谢。
回答by Alladinian
'=' is for assignment while '==' is for comparison. But in the case of string comparison you should use isEqualToString
method. Something like this:
'=' 用于赋值,而 '==' 用于比较。但是在字符串比较的情况下,您应该使用isEqualToString
方法。像这样的东西:
if ([magicButton.titleLabel.text isEqualToString: @"1"]) {
[magicButton setTitle:@"2" forState:UIControlStateNormal];
}
PS. Also note that you should get the UILabel
's text
property
附注。另请注意,您应该获取UILabel
'stext
属性
回答by Imirak
If you want to be changing the button text relative to what it is with no restrictions, you can't make a million if statements. You should get the value of the button title (if it even has a title) and just add 1 to it, like so:
如果您想不受限制地更改相对于它的按钮文本,则不能制作一百万条 if 语句。您应该获取按钮标题的值(如果它甚至有标题),然后将其加 1,如下所示:
NSString *string = randomButton.titleLabel.text;
if ([randomButton.titleLabel.text length] == 0) { //Check if there is not a title on the button
[randomButton setTitle:@"1" forState:UIControlStateNormal]; //And if there isn't, set it to "1"
}
else {
int yourInt = [string intValue]; //Convert to int
int nextInt = yourInt + 1; //Add one to value
NSString *finalString = [NSString stringWithFormat:@"%d",nextInt]; //Convert back to string
[randomButton setTitle:finalString forState:UIControlStateNormal]; //Finally set it as the title
}