将 UIButton 放在用 Swift 编写的 Xcode 中 iOS 应用程序中 UITextView 的文本末尾 [英] Place UIButton at the end of text in UITextView in iOS app in Xcode written in Swift

查看:19
本文介绍了将 UIButton 放在用 Swift 编写的 Xcode 中 iOS 应用程序中 UITextView 的文本末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的一个 ViewController 中有一个 UITextView.我想在文本末尾有一个允许推送通知"按钮.但是由于按钮是静态的,TextView 中的文本是动态的,具体取决于显示宽度,因此在某些设备和方向上看起来非常糟糕.

In one ViewController of my app there's a UITextView. I want to have an "Allow Push Notifications" button at the end of the text. But since a button is static a the text in the TextView is dynamical depending on display width it looks really bad on some devices and orientations.

有人知道如何解决这个问题吗?是否可以在 TextView 中插入按钮.或者我可以根据 TextView 内容高度对齐按钮吗?

Does anybody know how to solve this problem? Is there a possibility to insert a button in a TextView. Or can I align the button depending from TextView content height?

问候,大卫.

推荐答案

UITextView 来自 UIScrollView 的子类,您可以充分利用它来添加子视图任何普通的UIScrollView,诀窍是通过按钮+填充的高度来偏移文本视图的文本容器.例如:

UITextView subclasses from UIScrollView, you can use this to your advantage to add subviews to it as you would any normal UIScrollView, the trick is to offset the text view's text container by the height of the button + padding. For example:

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 500))
textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae fermentum tellus. Donec dui sem, viverra eu auctor eleifend, aliquet id lorem. Nam id sapien sed arcu auctor commodo nec nec nulla. Praesent id mi nec odio consequat varius id sit amet quam."

let buttonHeight: CGFloat = 44
let contentInset: CGFloat = 8

//inset the textView
textView.textContainerInset = UIEdgeInsets(top: contentInset, left: contentInset, bottom: (buttonHeight+contentInset*2), right: contentInset)

let button = UIButton(frame: CGRect(x: contentInset, y: textView.contentSize.height - buttonHeight - contentInset, width: textView.contentSize.width-contentInset*2, height: buttonHeight))

//setup your button here
button.setTitle("BUTTON", forState: UIControlState.Normal)
button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.lightGrayColor()

//Add the button to the text view
textView.addSubview(button)

这将为您提供以下输出:

This will give you the following output:

希望这会有所帮助!

这篇关于将 UIButton 放在用 Swift 编写的 Xcode 中 iOS 应用程序中 UITextView 的文本末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆