IOS改变UISearchBar中搜索框的高度

2025-05-29 0 40

一、系统的searchbar
1、uisearchbar的中子控件及其布局
uiview(直接子控件) frame 等于 searchbar的bounds,view的子控件及其布局

  • uisearchbarbackground(间接子控件) frame 等于searchbar的bounds
  • uisearchbartextfield(间接子控件) frame.origin等于(8.0, 6.0),即不等于searchbar的bounds

2、改变searchbar的frame只会影响其中搜索框的宽度,不会影响其高度,原因如下:

  • 系统searchbar中的uisearchbartextfield的高度默认固定为28
  • 左右边距固定为8,上下边距是父控件view的高度减去28除以2

二、改变uisearchbar的高度
1、方案
重写uisearchbar的子类(idsearchbar),重新布局uisearchbar子控件的布局
增加成员属性contentinset,控制uisearchbartextfield距离父控件的边距

  • 若用户没有设置contentinset,则计算出默认的contentinset
  • 若用户设置了contentinset,则根据最新的contentinset布局uisearchbartextfield

2、具体实现
重写uisearchbar的子类

?

1

2

3
class idsearchbar: uisearchbar {

}

增加成员属性contentinset(可选类型),控制uisearchbartextfield距离父控件的边距,监听其值的改变,重新布局searchbar子控件的布局

?

1

2

3

4

5
var contentinset: uiedgeinsets? {

didset {

self.layoutsubviews()

}

}

重写layoutsubviews()布局searchbar的子控件

?

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
override func layoutsubviews() {

super.layoutsubviews()

// view是searchbar中的唯一的直接子控件

for view in self.subviews {

// uisearchbarbackground与uisearchbartextfield是searchbar的简介子控件

for subview in view.subviews {

// 找到uisearchbartextfield

if subview.iskindofclass(uitextfield.classforcoder()) {

if let textfieldcontentinset = contentinset { // 若contentinset被赋值

// 根据contentinset改变uisearchbartextfield的布局

subview.frame = cgrect(x: textfieldcontentinset.left, y: textfieldcontentinset.top, width: self.bounds.width - textfieldcontentinset.left - textfieldcontentinset.right, height: self.bounds.height - textfieldcontentinset.top - textfieldcontentinset.bottom)

} else { // 若contentset未被赋值

// 设置uisearchbar中uisearchbartextfield的默认边距

let top: cgfloat = (self.bounds.height - 28.0) / 2.0

let bottom: cgfloat = top

let left: cgfloat = 8.0

let right: cgfloat = left

contentinset = uiedgeinsets(top: top, left: left, bottom: bottom, right: right)

}

}

}

}

}

三、idsearchbar使用示例
1、未设置contentinset
设置searchbar的frame

?

1
searchbar.frame = cgrect(x: 80, y: 100, width: 200, height: 40)

效果如图

IOS改变UISearchBar中搜索框的高度

2、设置contentinset
设置searchbar的frame

?

1
searchbar.frame = cgrect(x: 80, y: 100, width: 200, height: 40)

设置searchbar的contentinset

?

1

2
// 设置contentinset

searchbar.contentinset = uiedgeinsets(top: 0, left: 8, bottom: 0, right: 8)

效果如图

IOS改变UISearchBar中搜索框的高度

四、idsearchbar的设计原则
1、注意

  • uisearchbar默认是有自己默认的布局方式的
  • 设计idsearchbar旨在改变searbar中搜索框高度,但是可能会有改变宽的的需求

2、设计原则

  • 在没有改变searchbar中搜索框高度的需求时,需要使用uisearchbar的默认布局
  • 若需要改变searchbar中搜索框高度的需求时,需要按照需求来改变uisearchbar的布局
  • 为了增加可控性,在idsearchbar中增加成员属性contentinset来控制idsearchbar的内边距

以上就是本文的全部内容,希望对大家的学习有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 IOS改变UISearchBar中搜索框的高度 https://www.kuaiidc.com/93865.html

相关文章

发表评论
暂无评论