ios - 用 UITextField 替换 UiNavigationItem.Title 的错误布局

标签 ios objective-c uitextfield autolayout uinavigationitem

我不会用 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 的定位和大小时遇到​​问题:

portrait landscape

我希望 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 边界以适应 textplaceHolder喜欢

- (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/

相关文章:

iOS segues 数据不被传递

ios - 无法将 UITextField 添加到 UIScrollView

ios - UITextField 文本在动态类型调整大小后垂直移动

ios - Phonegap 1.3 captureImage到Photo Library并在HTML/App界面显示图像

ios - 图像不会动画

ios - 在 Swift 中声明采用符合 “can be multiplied” 的泛型类型的函数

iphone - 转换时的 UITextField 垂直文本对齐

ios - 从 Swift 调用 C 函数

objective-c - c风格的指针和id风格的对象有什么区别?

objective-c - NSCollectionView 不显示其内容