【问题标题】:Delete spaces between words textfield删除单词文本字段之间的空格
【发布时间】:2013-10-21 10:39:52
【问题描述】:

如果您需要输入城市名称,我有一个 UITextField。该城市名称链接到一个 url:例如 mywebsite/oslo

但是,当我进入纽约时,它不是一个正确的网址。我的网站/纽约 必须是这个http://www.website.com/New-York 如何制作一个 UITextField 替换空格:--> -

感谢您的帮助!

- (void)configureControls {


[self.activityIndicator stopAnimating];

[UIView animateWithDuration:1.5 animations:^{

    if (self.weatherModel.lastLoadFailed) {
        self.locationTextField.enabled = YES;
        self.saveButton.hidden = NO;
        self.activityIndicator.hidden = YES;
        return;
    }

    self.settingsModel.location = self.locationTextField.text;


    PWForecastModel *forecast = self.weatherModel.sevenDayForecast[0];
    NSString *backgroundName = [PWHelper backgroundFileNameForConditionCode:forecast.conditions.conditionCode asDaytime:[[NSDate date] isDayTime]];
    if (![[NSDate date] isDayTime]) {
        [self styleControlsForDarkBackground];
    }
    self.backgroundImageView.image = [UIImage imageNamed:backgroundName];
    self.locationLabel.text = [NSString stringWithFormat:@"%@",self.weatherModel.cityName];
}];

}

【问题讨论】:

    标签: ios xcode uitextfield spaces


    【解决方案1】:

    使用这个

     [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    

    【讨论】:

    • 仅此,删除字符串开头和结尾的字符,
    【解决方案2】:

    您需要调用委托方法textFieldShouldEndEditing。那里你只需使用这个 stringByReplacingOccurrencesOfString 。或者也可以在任何事件上使用它。就这样 。希望这会有所帮助。

    参考:

       -(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
           //    NSString *str=  [textField.text stringByReplacingOccurrencesOfString:@" " withString:@"-"];
            //    NSLog(@"Testing: %@",str);
     textField.text = [NSString stringWithFormat:@"www.myweb.com/%@",[textField.text stringByReplacingOccurrencesOfString:@" " withString:@"-"]];
                return YES;
            }
    

    我想,你只需要这个:

    [self.weatherModel.cityName stringByReplacingOccurrencesOfString:@" " withString:@"-"];
    

    【讨论】:

    • 这行得通吗? self.locationLabel.text = [NSString stringWithFormat:@"%@",[self.weatherModel.cityName stringByReplacingOccurrencesOfString:@" " withString:@"-"]];
    • 如果这个 self.weatherModel.cityName 可以得到正确的值。然后它应该工作..
    • 多余的代码,[NSString stringWithFormat:@"%@" 不需要,当然也删除最后一个]
    • self.weatherModel.cityName 是 NSString
    • 那你有什么问题..?
    【解决方案3】:

    试试这个

    NSString *string = @"Hi I am Indra          ";
    NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                      [NSCharacterSet whitespaceCharacterSet]];
    

    用于替换字符串中的空格

    NSString *str = @"This is a string";
    
    str = [str stringByReplacingOccurrencesOfString:@" "
                                         withString:@""];
    

    【讨论】:

    • 仅此,删除字符串开头和结尾的字符,
    • 所以你想删除字符串之间的空格??
    • 我没有。但是Op要求就是这样。阅读那个
    • 在字符串之间是。比如纽约或者旧金山。因为否则它不是一个正确的 URL。