UI定制 - UISearchBar:居左显示

UISearchBar 居左显示

1 - 代码示例:新建 UISearchBar 子类 UINoMidSearchBar

// - UINoMidSearchBar.h

#import <UIKit/UIKit.h>
@interface UINoMidSearchBar : UISearchBar
@property (nonatomic, assign, setter = setHasCentredPlaceholder:) BOOL hasCentredPlaceholder;
@end

// - UINoMidSearchBar.m

复制代码
 1 #import "UINoMidSearchBar.h"
 2 @implementation UINoMidSearchBar
 3 
 4 - (instancetype)initWithFrame:(CGRect)frame{
 5     
 6     self = [super initWithFrame:frame];
 7     if (self) {
 8         self.hasCentredPlaceholder = YES;
 9     }
10     return self;
11 }
12 
13 -(void)setHasCentredPlaceholder:(BOOL)hasCentredPlaceholder{
14 
15     _hasCentredPlaceholder = hasCentredPlaceholder;
16     SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);
17     if ([self respondsToSelector:centerSelector]){
18     
19         NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
20     
21         NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
22         [invocation setTarget:self];
23         [invocation setSelector:centerSelector];
24         [invocation setArgument:&_hasCentredPlaceholder atIndex:2];
25         [invocation invoke];
26     }
27 }
28 
29 @end
复制代码

2 - 如何使用

复制代码
 1 #import "ViewController.h"
 2 #import "UINoMidSearchBar.h"
 3 @interface ViewController ()
 4 
 5 @property(strong,nonatomic)UINoMidSearchBar *testSearchBar;// 搜索框
 6 
 7 @end
 8 
 9 @implementation ViewController
10 
11 - (void)viewDidLoad {
12     [super viewDidLoad];
13     self.view.backgroundColor = [UIColor whiteColor];
14 
15     // 搜索框
16     self.testSearchBar = [[UINoMidSearchBar alloc] initWithFrame:CGRectMake(15, 200, self.view.frame.size.width-30, 50)];
17     self.testSearchBar.placeholder = @"窈窕淑女";
18     self.testSearchBar.hasCentredPlaceholder = NO;// 占位字符默认非居中
19     //[self.testSearchBar setImage:[UIImage imageNamed:@""] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];// 修改搜索图片(放大镜)
20     //[[[self.testSearchBar.subviews objectAtIndex:0].subviews objectAtIndex:1] setTintColor:[UIColor greenColor]];// 光标颜色
21     //self.testSearchBar.searchBarStyle = UISearchBarStyleMinimal;// 去边框
22     [self.testSearchBar setKeyboardType:UIKeyboardTypeEmailAddress];
23     [self.view addSubview:_testSearchBar];
24 
25 }
26 
27 
28 @end
复制代码

运行效果

 

 

posted on   低头捡石頭  阅读(33)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示