我不会用 UITextfield 替换 UINavigationItem.title。
为了做到这一点,我在 viewDidLoad 中添加了 TextField
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
textField.text = @"";
textField.placeholder = @"set title here";
textField.font = [UIFont fontWithName:@"Futura-Medium" size:19.0];
textField.textColor = [UIColor whiteColor];
textField.textAlignment = NSTextAlignmentCenter;
textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.delegate = self;
self.navigationItem.titleView = textField;
但我在执行 TextField 的定位和大小时遇到问题:
我希望 TextField 的行为类似于 NavigationItem.title
有什么想法吗?
提前致谢
---这是我的课---
#import "CustomCategoryViewController.h"
@interface CustomCategoryViewController ()<UITextFieldDelegate>
@end
@implementation CustomCategoryViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(@"%f",self.navigationController.navigationItem.titleView.frame.size.height);
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 30)];
textField.text = @"";
textField.placeholder = @"set title here";
textField.font = [UIFont fontWithName:@"Futura-Medium" size:19.0];
textField.textColor = [UIColor whiteColor];
textField.textAlignment = NSTextAlignmentCenter;
textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.delegate = self;
self.navigationItem.titleView = textField;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - TextField Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *set = [NSCharacterSet newlineCharacterSet];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound){
[textField endEditing:YES];
}
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
//self.commonName = @"";
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField.text && ![textField.text isEqualToString:@""]) {
CGRect rect = [textField textRectForBounds:textField.bounds];
[textField setBounds:CGRectMake(0, 0, rect.size.width, rect.size.height)];
}
else{
CGRect rect = [textField placeholderRectForBounds:textField.bounds];
[textField setBounds:CGRectMake(0, 0, rect.size.width, rect.size.height)];
}
}
#pragma mark - Keyboard
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
}
#pragma mark - Interface Orientation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// Code here will execute before the rotation begins.
// Equivalent to placing it in the deprecated method -[willRotateToInterfaceOrientation:duration:]
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Place code here to perform animations during the rotation. You can leave this block empty if not necessary.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
});
});
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Code here will execute after the rotation has finished.
// Equivalent to placing it in the deprecated method -[didRotateFromInterfaceOrientation:]
}];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
最佳答案
当前,您的 textField 宽度为 150,并且其内容保持在中心位置,因此当您有较长的 barButton 时,您会看到文本 float 到一侧。
每次编辑 textField 后,您都需要设置 textField 边界以适应 text 或 placeHolder喜欢
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField.text && ![textField.text isEqualToString:@""]) {
CGRect textRect = [textField.text boundingRectWithSize:CGSizeMake(300,30)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:textField.font}
context:nil];
[textField setBounds:CGRectMake(0, 0, textRect.size.width, textRect.size.height)];
}
else{
CGRect textRect = [textField.placeholder boundingRectWithSize:CGSizeMake(300,30)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:textField.font}
context:nil];
[textField setBounds:CGRectMake(0, 0, textRect.size.width, textRect.size.height)];
}
}
在此之后,您的 textField 的大小将与其内容完全匹配,并且它将位于 navigationBar 的中心。
关于ios - 用 UITextField 替换 UiNavigationItem.Title 的错误布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961592/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie