去除 UITextView 内边距
// 去除 textView 左右边距:
tv.textContainer.lineFragmentPadding = 0
// 去除 textView 上下边距:
tv.textContainerInset = UIEdgeInsets.zero
编辑时文本间隙
let style = NSMutableParagraphStyle()
style.lineSpacing = 5
tv.typingAttributes = [NSAttributedStringKey.paragraphStyle.rawValue: style]
键盘添加完成按钮及事件
WechatIMG1.pngswift
/// 键盘添加完成按钮及事件
public extension UITextView {
static var doneKey = "doneKey"
private var doneClosure: (()->Void)? {
set {
objc_setAssociatedObject(
self,
&UITextView.doneKey,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
get {
return objc_getAssociatedObject(self, &UITextView.doneKey) as? ()->Void
}
}
func showDoneButton(_ callback:(()->Void)? = nil) {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: Screen.width, height: 35.0))
toolbar.tintColor = UIColor.systemBlue
toolbar.backgroundColor = UIColor(red: 230.0/255.0, green: 230.0/255.0, blue: 230.0/255.0, alpha: 1)
let flexibleSpaceBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
let doneBtn = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.plain, target: self, action: #selector(doneAction))
toolbar.items = [flexibleSpaceBtn, doneBtn]
self.inputAccessoryView = toolbar
doneClosure = callback
}
@objc func doneAction() {
self.resignFirstResponder()
doneClosure?()
}
}
使用
let tv = UITextView()
tv.showDoneButton()
oc
.h文件
#import <UIKit/UIKit.h>
@interface UITextView (XXExtension)
/// 键盘上方显示"完成“按钮
/// @param callback 回调
- (void)xx_showDoneButton:(void(^)(void))callback;
@end
.m文件
#import "UITextView+XXExtension.h"
#import "XXMacros.h"
#import <objc/runtime.h>
@interface UITextView ()
@property (nonatomic, copy) void(^doneBlock)(void);
@end
@implementation UITextView (XXExtension)
- (void)xx_showDoneButton:(void(^)(void))callback {
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35)];
toolbar.tintColor = UIColor.systemBlueColor;
toolbar.backgroundColor = [[UIColor alloc] initWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
UIBarButtonItem *flexibleSpaceBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(xx_doneAction)];
toolbar.items = @[flexibleSpaceBtn, doneBtn];
self.inputAccessoryView = toolbar;
self.doneBlock = callback;
}
- (void)xx_doneAction {
if (self.doneBlock) {
self.doneBlock();
}
}
- (void)setDoneBlock:(void (^)(void))doneBlock {
objc_setAssociatedObject(self, @selector(doneBlock), doneBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (void (^)(void))doneBlock {
return objc_getAssociatedObject(self, @selector(doneBlock));
}
@end
网友评论