UISearchBar 放大镜等居左,及placeholder偏上的问题

本文介绍如何使用Objective-C针对UISearchBar进行个性化定制,包括调整搜索栏的占位符位置、设置输入框的文字颜色、字体及文本偏移量,以及为搜索栏设置图标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不说了,直接上代码

1、解决居左的问题,创建UISearchBar的category类,添加下面的方法

-(void)setLeftPlaceholder:(NSString *)placeholder {
    
    self.placeholder = placeholder;
    
    SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);
    if ([self respondsToSelector:centerSelector]) {
        BOOL centeredPlaceholder = NO;
        NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:self];
        [invocation setSelector:centerSelector];
        [invocation setArgument:¢eredPlaceholder atIndex:2];
        [invocation invoke];
    }
}

2、输入框的文字颜色、字体、文本偏移问题

UIFont *font = xxxx // 字体
        
        /* 这种不行,不知道为什么
        CGFloat imageHeight = iconImage.size.height; // 14
        CGFloat lineHeight = font.lineHeight; // 16.391999999999999
        CGFloat offset = (imageHeight-lineHeight)/2.0; // -1.1959999999999997
         */
        CGFloat offset = -0.7;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:placeHolder
                                                                                             attributes:@{
                                                                                                          NSForegroundColorAttributeName: 颜色值,
                                                                                                          NSFontAttributeName : font,
                                                                                                          NSBaselineOffsetAttributeName : @(offset),
                                                                                                          }];
        
        
        [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setAttributedPlaceholder:attributedString];


3、设置图标

UIImage *iconImage = [UIImage imageNamed:@"index_icon_search"];
        [_searchBar setImage:iconImage forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值