ios - 在用 Swift 编写的 Xcode 中的 iOS 应用程序中的 UITextView 中,将 UIButton 放置在文本的末尾

标签 ios swift uibutton uitextview

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

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

问候, 大卫。

最佳答案

UITextViewUIScrollView 的子类,您可以利用它来为它添加 subview ,就像添加任何普通的 UIScrollView 一样,技巧是通过按钮+填充的高度来偏移 TextView 的文本容器。例如:

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)

这将为您提供以下输出:

enter image description here

希望这对您有所帮助!

关于ios - 在用 Swift 编写的 Xcode 中的 iOS 应用程序中的 UITextView 中,将 UIButton 放置在文本的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37674139/

相关文章:

objective-c - 是否可以更改 UIButtons 背景颜色?

iphone - 为什么应用程序的图标在 iCloud 设置中显示为空白?

ios - UITableView 拖放到表外 = 崩溃

iphone - 如何打开 iPhone 的默认浏览器?

ios - 图像在 ios 中滚动时波动

ios - 将三个动画间隔一秒的最佳方法是什么?

ios - 如何创建虚线 uibutton

iphone - 在应用程序启动时加载一张图片,该图片可以从网上更新

ios - 带有自定义的 UIButton。按下时背景看起来很糟糕

ios - Realm Objective-C 写入数据库时​​如何忽略已经存在的相同主键?